babylon.no-module.max.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. /** @hidden */
  414. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  415. // Rebuild shaders source code
  416. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  417. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  418. vertexCode = prefix + vertexCode;
  419. fragmentCode = prefix + fragmentCode;
  420. // Number lines of shaders source code
  421. var i = 2;
  422. var regex = /\n/gm;
  423. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  424. i = 2;
  425. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  426. // Dump shaders name and formatted source code
  427. if (this.name.vertexElement) {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  430. }
  431. else if (this.name.vertex) {
  432. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  433. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  434. }
  435. else {
  436. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  437. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  438. }
  439. };
  440. ;
  441. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  442. var preparedSourceCode = this._processPrecision(sourceCode);
  443. if (this._engine.webGLVersion == 1) {
  444. callback(preparedSourceCode);
  445. return;
  446. }
  447. // Already converted
  448. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  449. callback(preparedSourceCode.replace("#version 300 es", ""));
  450. return;
  451. }
  452. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  453. // Remove extensions
  454. // #extension GL_OES_standard_derivatives : enable
  455. // #extension GL_EXT_shader_texture_lod : enable
  456. // #extension GL_EXT_frag_depth : enable
  457. // #extension GL_EXT_draw_buffers : require
  458. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  459. var result = preparedSourceCode.replace(regex, "");
  460. // Migrate to GLSL v300
  461. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  462. result = result.replace(/attribute[ \t]/g, "in ");
  463. result = result.replace(/[ \t]attribute/g, " in");
  464. if (isFragment) {
  465. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  467. result = result.replace(/texture2D\s*\(/g, "texture(");
  468. result = result.replace(/textureCube\s*\(/g, "texture(");
  469. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  470. result = result.replace(/gl_FragColor/g, "glFragColor");
  471. result = result.replace(/gl_FragData/g, "glFragData");
  472. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  473. }
  474. callback(result);
  475. };
  476. Effect.prototype._processIncludes = function (sourceCode, callback) {
  477. var _this = this;
  478. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  479. var match = regex.exec(sourceCode);
  480. var returnValue = new String(sourceCode);
  481. while (match != null) {
  482. var includeFile = match[1];
  483. // Uniform declaration
  484. if (includeFile.indexOf("__decl__") !== -1) {
  485. includeFile = includeFile.replace(/__decl__/, "");
  486. if (this._engine.supportsUniformBuffers) {
  487. includeFile = includeFile.replace(/Vertex/, "Ubo");
  488. includeFile = includeFile.replace(/Fragment/, "Ubo");
  489. }
  490. includeFile = includeFile + "Declaration";
  491. }
  492. if (Effect.IncludesShadersStore[includeFile]) {
  493. // Substitution
  494. var includeContent = Effect.IncludesShadersStore[includeFile];
  495. if (match[2]) {
  496. var splits = match[3].split(",");
  497. for (var index = 0; index < splits.length; index += 2) {
  498. var source = new RegExp(splits[index], "g");
  499. var dest = splits[index + 1];
  500. includeContent = includeContent.replace(source, dest);
  501. }
  502. }
  503. if (match[4]) {
  504. var indexString = match[5];
  505. if (indexString.indexOf("..") !== -1) {
  506. var indexSplits = indexString.split("..");
  507. var minIndex = parseInt(indexSplits[0]);
  508. var maxIndex = parseInt(indexSplits[1]);
  509. var sourceIncludeContent = includeContent.slice(0);
  510. includeContent = "";
  511. if (isNaN(maxIndex)) {
  512. maxIndex = this._indexParameters[indexSplits[1]];
  513. }
  514. for (var i = minIndex; i < maxIndex; i++) {
  515. if (!this._engine.supportsUniformBuffers) {
  516. // Ubo replacement
  517. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  518. return p1 + "{X}";
  519. });
  520. }
  521. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  522. }
  523. }
  524. else {
  525. if (!this._engine.supportsUniformBuffers) {
  526. // Ubo replacement
  527. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  528. return p1 + "{X}";
  529. });
  530. }
  531. includeContent = includeContent.replace(/\{X\}/g, indexString);
  532. }
  533. }
  534. // Replace
  535. returnValue = returnValue.replace(match[0], includeContent);
  536. }
  537. else {
  538. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  539. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  540. Effect.IncludesShadersStore[includeFile] = fileContent;
  541. _this._processIncludes(returnValue, callback);
  542. });
  543. return;
  544. }
  545. match = regex.exec(sourceCode);
  546. }
  547. callback(returnValue);
  548. };
  549. Effect.prototype._processPrecision = function (source) {
  550. if (source.indexOf("precision highp float") === -1) {
  551. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  552. source = "precision mediump float;\n" + source;
  553. }
  554. else {
  555. source = "precision highp float;\n" + source;
  556. }
  557. }
  558. else {
  559. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  560. source = source.replace("precision highp float", "precision mediump float");
  561. }
  562. }
  563. return source;
  564. };
  565. /**
  566. * Recompiles the webGL program
  567. * @param vertexSourceCode The source code for the vertex shader.
  568. * @param fragmentSourceCode The source code for the fragment shader.
  569. * @param onCompiled Callback called when completed.
  570. * @param onError Callback called on error.
  571. */
  572. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  573. var _this = this;
  574. this._isReady = false;
  575. this._vertexSourceCodeOverride = vertexSourceCode;
  576. this._fragmentSourceCodeOverride = fragmentSourceCode;
  577. this.onError = function (effect, error) {
  578. if (onError) {
  579. onError(error);
  580. }
  581. };
  582. this.onCompiled = function () {
  583. var scenes = _this.getEngine().scenes;
  584. for (var i = 0; i < scenes.length; i++) {
  585. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  586. }
  587. if (onCompiled) {
  588. onCompiled(_this._program);
  589. }
  590. };
  591. this._fallbacks = null;
  592. this._prepareEffect();
  593. };
  594. /**
  595. * Gets the uniform locations of the the specified variable names
  596. * @param names THe names of the variables to lookup.
  597. * @returns Array of locations in the same order as variable names.
  598. */
  599. Effect.prototype.getSpecificUniformLocations = function (names) {
  600. var engine = this._engine;
  601. return engine.getUniforms(this._program, names);
  602. };
  603. /**
  604. * Prepares the effect
  605. */
  606. Effect.prototype._prepareEffect = function () {
  607. var attributesNames = this._attributesNames;
  608. var defines = this.defines;
  609. var fallbacks = this._fallbacks;
  610. this._valueCache = {};
  611. var previousProgram = this._program;
  612. try {
  613. var engine = this._engine;
  614. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  615. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  616. }
  617. else {
  618. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  619. }
  620. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  621. if (engine.supportsUniformBuffers) {
  622. for (var name in this._uniformBuffersNames) {
  623. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  624. }
  625. }
  626. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  627. this._attributes = engine.getAttributes(this._program, attributesNames);
  628. var index;
  629. for (index = 0; index < this._samplers.length; index++) {
  630. var sampler = this.getUniform(this._samplers[index]);
  631. if (sampler == null) {
  632. this._samplers.splice(index, 1);
  633. index--;
  634. }
  635. }
  636. engine.bindSamplers(this);
  637. this._compilationError = "";
  638. this._isReady = true;
  639. if (this.onCompiled) {
  640. this.onCompiled(this);
  641. }
  642. this.onCompileObservable.notifyObservers(this);
  643. this.onCompileObservable.clear();
  644. // Unbind mesh reference in fallbacks
  645. if (this._fallbacks) {
  646. this._fallbacks.unBindMesh();
  647. }
  648. if (previousProgram) {
  649. this.getEngine()._deleteProgram(previousProgram);
  650. }
  651. }
  652. catch (e) {
  653. this._compilationError = e.message;
  654. // Let's go through fallbacks then
  655. BABYLON.Tools.Error("Unable to compile effect:");
  656. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  657. return " " + uniform;
  658. }));
  659. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  660. return " " + attribute;
  661. }));
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. if (x === void 0) { x = 0; }
  2190. if (y === void 0) { y = 0; }
  2191. this.x = x;
  2192. this.y = y;
  2193. }
  2194. /**
  2195. * Gets a string with the Vector2 coordinates
  2196. * @returns a string with the Vector2 coordinates
  2197. */
  2198. Vector2.prototype.toString = function () {
  2199. return "{X: " + this.x + " Y:" + this.y + "}";
  2200. };
  2201. /**
  2202. * Gets class name
  2203. * @returns the string "Vector2"
  2204. */
  2205. Vector2.prototype.getClassName = function () {
  2206. return "Vector2";
  2207. };
  2208. /**
  2209. * Gets current vector hash code
  2210. * @returns the Vector2 hash code as a number
  2211. */
  2212. Vector2.prototype.getHashCode = function () {
  2213. var hash = this.x || 0;
  2214. hash = (hash * 397) ^ (this.y || 0);
  2215. return hash;
  2216. };
  2217. // Operators
  2218. /**
  2219. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2220. * @param array defines the source array
  2221. * @param index defines the offset in source array
  2222. * @returns the current Vector2
  2223. */
  2224. Vector2.prototype.toArray = function (array, index) {
  2225. if (index === void 0) { index = 0; }
  2226. array[index] = this.x;
  2227. array[index + 1] = this.y;
  2228. return this;
  2229. };
  2230. /**
  2231. * Copy the current vector to an array
  2232. * @returns a new array with 2 elements: the Vector2 coordinates.
  2233. */
  2234. Vector2.prototype.asArray = function () {
  2235. var result = new Array();
  2236. this.toArray(result, 0);
  2237. return result;
  2238. };
  2239. /**
  2240. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2241. * @param source defines the source Vector2
  2242. * @returns the current updated Vector2
  2243. */
  2244. Vector2.prototype.copyFrom = function (source) {
  2245. this.x = source.x;
  2246. this.y = source.y;
  2247. return this;
  2248. };
  2249. /**
  2250. * Sets the Vector2 coordinates with the given floats
  2251. * @param x defines the first coordinate
  2252. * @param y defines the second coordinate
  2253. * @returns the current updated Vector2
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given floats
  2262. * @param x defines the first coordinate
  2263. * @param y defines the second coordinate
  2264. * @returns the current updated Vector2
  2265. */
  2266. Vector2.prototype.set = function (x, y) {
  2267. return this.copyFromFloats(x, y);
  2268. };
  2269. /**
  2270. * Add another vector with the current one
  2271. * @param otherVector defines the other vector
  2272. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2273. */
  2274. Vector2.prototype.add = function (otherVector) {
  2275. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2276. };
  2277. /**
  2278. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2279. * @param otherVector defines the other vector
  2280. * @param result defines the target vector
  2281. * @returns the unmodified current Vector2
  2282. */
  2283. Vector2.prototype.addToRef = function (otherVector, result) {
  2284. result.x = this.x + otherVector.x;
  2285. result.y = this.y + otherVector.y;
  2286. return this;
  2287. };
  2288. /**
  2289. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2290. * @param otherVector defines the other vector
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.addInPlace = function (otherVector) {
  2294. this.x += otherVector.x;
  2295. this.y += otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2300. * @param otherVector defines the other vector
  2301. * @returns a new Vector2
  2302. */
  2303. Vector2.prototype.addVector3 = function (otherVector) {
  2304. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2305. };
  2306. /**
  2307. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2308. * @param otherVector defines the other vector
  2309. * @returns a new Vector2
  2310. */
  2311. Vector2.prototype.subtract = function (otherVector) {
  2312. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2316. * @param otherVector defines the other vector
  2317. * @param result defines the target vector
  2318. * @returns the unmodified current Vector2
  2319. */
  2320. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2321. result.x = this.x - otherVector.x;
  2322. result.y = this.y - otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns the current updated Vector2
  2329. */
  2330. Vector2.prototype.subtractInPlace = function (otherVector) {
  2331. this.x -= otherVector.x;
  2332. this.y -= otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Multiplies in place the current Vector2 coordinates by the given ones
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2341. this.x *= otherVector.x;
  2342. this.y *= otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.multiply = function (otherVector) {
  2351. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2352. };
  2353. /**
  2354. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2355. * @param otherVector defines the other vector
  2356. * @param result defines the target vector
  2357. * @returns the unmodified current Vector2
  2358. */
  2359. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2360. result.x = this.x * otherVector.x;
  2361. result.y = this.y * otherVector.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2366. * @param x defines the first coordinate
  2367. * @param y defines the second coordinate
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.multiplyByFloats = function (x, y) {
  2371. return new Vector2(this.x * x, this.y * y);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2375. * @param otherVector defines the other vector
  2376. * @returns a new Vector2
  2377. */
  2378. Vector2.prototype.divide = function (otherVector) {
  2379. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2380. };
  2381. /**
  2382. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2383. * @param otherVector defines the other vector
  2384. * @param result defines the target vector
  2385. * @returns the unmodified current Vector2
  2386. */
  2387. Vector2.prototype.divideToRef = function (otherVector, result) {
  2388. result.x = this.x / otherVector.x;
  2389. result.y = this.y / otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Divides the current Vector3 coordinates by the given ones
  2394. * @param otherVector defines the other vector
  2395. * @returns the current updated Vector2
  2396. */
  2397. Vector2.prototype.divideInPlace = function (otherVector) {
  2398. return this.divideToRef(otherVector, this);
  2399. };
  2400. /**
  2401. * Gets a new Vector2 with current Vector2 negated coordinates
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.negate = function () {
  2405. return new Vector2(-this.x, -this.y);
  2406. };
  2407. /**
  2408. * Multiply the Vector2 coordinates by scale
  2409. * @param scale defines the scaling factor
  2410. * @returns the current updated Vector2
  2411. */
  2412. Vector2.prototype.scaleInPlace = function (scale) {
  2413. this.x *= scale;
  2414. this.y *= scale;
  2415. return this;
  2416. };
  2417. /**
  2418. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2419. * @param scale defines the scaling factor
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.scale = function (scale) {
  2423. var result = new Vector2(0, 0);
  2424. this.scaleToRef(scale, result);
  2425. return result;
  2426. };
  2427. /**
  2428. * Scale the current Vector2 values by a factor to a given Vector2
  2429. * @param scale defines the scale factor
  2430. * @param result defines the Vector2 object where to store the result
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.scaleToRef = function (scale, result) {
  2434. result.x = this.x * scale;
  2435. result.y = this.y * scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2440. * @param scale defines the scale factor
  2441. * @param result defines the Vector2 object where to store the result
  2442. * @returns the unmodified current Vector2
  2443. */
  2444. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2445. result.x += this.x * scale;
  2446. result.y += this.y * scale;
  2447. return this;
  2448. };
  2449. /**
  2450. * Gets a boolean if two vectors are equals
  2451. * @param otherVector defines the other vector
  2452. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2453. */
  2454. Vector2.prototype.equals = function (otherVector) {
  2455. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2456. };
  2457. /**
  2458. * Gets a boolean if two vectors are equals (using an epsilon value)
  2459. * @param otherVector defines the other vector
  2460. * @param epsilon defines the minimal distance to consider equality
  2461. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2462. */
  2463. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2464. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2465. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2466. };
  2467. // Properties
  2468. /**
  2469. * Gets the length of the vector
  2470. * @returns the vector length (float)
  2471. */
  2472. Vector2.prototype.length = function () {
  2473. return Math.sqrt(this.x * this.x + this.y * this.y);
  2474. };
  2475. /**
  2476. * Gets the vector squared length
  2477. * @returns the vector squared length (float)
  2478. */
  2479. Vector2.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y);
  2481. };
  2482. // Methods
  2483. /**
  2484. * Normalize the vector
  2485. * @returns the current updated Vector2
  2486. */
  2487. Vector2.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a new Vector2 copied from the Vector2
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.clone = function () {
  2501. return new Vector2(this.x, this.y);
  2502. };
  2503. // Statics
  2504. /**
  2505. * Gets a new Vector2(0, 0)
  2506. * @returns a new Vector2
  2507. */
  2508. Vector2.Zero = function () {
  2509. return new Vector2(0, 0);
  2510. };
  2511. /**
  2512. * Gets a new Vector2(1, 1)
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.One = function () {
  2516. return new Vector2(1, 1);
  2517. };
  2518. /**
  2519. * Gets a new Vector2 set from the given index element of the given array
  2520. * @param array defines the data source
  2521. * @param offset defines the offset in the data source
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.FromArray = function (array, offset) {
  2525. if (offset === void 0) { offset = 0; }
  2526. return new Vector2(array[offset], array[offset + 1]);
  2527. };
  2528. /**
  2529. * Sets "result" from the given index element of the given array
  2530. * @param array defines the data source
  2531. * @param offset defines the offset in the data source
  2532. * @param result defines the target vector
  2533. */
  2534. Vector2.FromArrayToRef = function (array, offset, result) {
  2535. result.x = array[offset];
  2536. result.y = array[offset + 1];
  2537. };
  2538. /**
  2539. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2540. * @param value1 defines 1st point of control
  2541. * @param value2 defines 2nd point of control
  2542. * @param value3 defines 3rd point of control
  2543. * @param value4 defines 4th point of control
  2544. * @param amount defines the interpolation factor
  2545. * @returns a new Vector2
  2546. */
  2547. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2548. var squared = amount * amount;
  2549. var cubed = amount * squared;
  2550. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2551. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2552. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2553. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2554. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2555. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2556. return new Vector2(x, y);
  2557. };
  2558. /**
  2559. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2560. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2561. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2562. * @param value defines the value to clamp
  2563. * @param min defines the lower limit
  2564. * @param max defines the upper limit
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.Clamp = function (value, min, max) {
  2568. var x = value.x;
  2569. x = (x > max.x) ? max.x : x;
  2570. x = (x < min.x) ? min.x : x;
  2571. var y = value.y;
  2572. y = (y > max.y) ? max.y : y;
  2573. y = (y < min.y) ? min.y : y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2578. * @param value1 defines the 1st control point
  2579. * @param tangent1 defines the outgoing tangent
  2580. * @param value2 defines the 2nd control point
  2581. * @param tangent2 defines the incoming tangent
  2582. * @param amount defines the interpolation factor
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2586. var squared = amount * amount;
  2587. var cubed = amount * squared;
  2588. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2589. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2590. var part3 = (cubed - (2.0 * squared)) + amount;
  2591. var part4 = cubed - squared;
  2592. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2593. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2594. return new Vector2(x, y);
  2595. };
  2596. /**
  2597. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2598. * @param start defines the start vector
  2599. * @param end defines the end vector
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Lerp = function (start, end, amount) {
  2604. var x = start.x + ((end.x - start.x) * amount);
  2605. var y = start.y + ((end.y - start.y) * amount);
  2606. return new Vector2(x, y);
  2607. };
  2608. /**
  2609. * Gets the dot product of the vector "left" and the vector "right"
  2610. * @param left defines first vector
  2611. * @param right defines second vector
  2612. * @returns the dot product (float)
  2613. */
  2614. Vector2.Dot = function (left, right) {
  2615. return left.x * right.x + left.y * right.y;
  2616. };
  2617. /**
  2618. * Returns a new Vector2 equal to the normalized given vector
  2619. * @param vector defines the vector to normalize
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.Normalize = function (vector) {
  2623. var newVector = vector.clone();
  2624. newVector.normalize();
  2625. return newVector;
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2629. * @param left defines 1st vector
  2630. * @param right defines 2nd vector
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.Minimize = function (left, right) {
  2634. var x = (left.x < right.x) ? left.x : right.x;
  2635. var y = (left.y < right.y) ? left.y : right.y;
  2636. return new Vector2(x, y);
  2637. };
  2638. /**
  2639. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2640. * @param left defines 1st vector
  2641. * @param right defines 2nd vector
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Maximize = function (left, right) {
  2645. var x = (left.x > right.x) ? left.x : right.x;
  2646. var y = (left.y > right.y) ? left.y : right.y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2651. * @param vector defines the vector to transform
  2652. * @param transformation defines the matrix to apply
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Transform = function (vector, transformation) {
  2656. var r = Vector2.Zero();
  2657. Vector2.TransformToRef(vector, transformation, r);
  2658. return r;
  2659. };
  2660. /**
  2661. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2662. * @param vector defines the vector to transform
  2663. * @param transformation defines the matrix to apply
  2664. * @param result defines the target vector
  2665. */
  2666. Vector2.TransformToRef = function (vector, transformation, result) {
  2667. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2668. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2669. result.x = x;
  2670. result.y = y;
  2671. };
  2672. /**
  2673. * Determines if a given vector is included in a triangle
  2674. * @param p defines the vector to test
  2675. * @param p0 defines 1st triangle point
  2676. * @param p1 defines 2nd triangle point
  2677. * @param p2 defines 3rd triangle point
  2678. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2679. */
  2680. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2681. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2682. var sign = a < 0 ? -1 : 1;
  2683. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2684. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2685. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2686. };
  2687. /**
  2688. * Gets the distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the distance between vectors
  2692. */
  2693. Vector2.Distance = function (value1, value2) {
  2694. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2695. };
  2696. /**
  2697. * Returns the squared distance between the vectors "value1" and "value2"
  2698. * @param value1 defines first vector
  2699. * @param value2 defines second vector
  2700. * @returns the squared distance between vectors
  2701. */
  2702. Vector2.DistanceSquared = function (value1, value2) {
  2703. var x = value1.x - value2.x;
  2704. var y = value1.y - value2.y;
  2705. return (x * x) + (y * y);
  2706. };
  2707. /**
  2708. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2709. * @param value1 defines first vector
  2710. * @param value2 defines second vector
  2711. * @returns a new Vector2
  2712. */
  2713. Vector2.Center = function (value1, value2) {
  2714. var center = value1.add(value2);
  2715. center.scaleInPlace(0.5);
  2716. return center;
  2717. };
  2718. /**
  2719. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2720. * @param p defines the middle point
  2721. * @param segA defines one point of the segment
  2722. * @param segB defines the other point of the segment
  2723. * @returns the shortest distance
  2724. */
  2725. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2726. var l2 = Vector2.DistanceSquared(segA, segB);
  2727. if (l2 === 0.0) {
  2728. return Vector2.Distance(p, segA);
  2729. }
  2730. var v = segB.subtract(segA);
  2731. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2732. var proj = segA.add(v.multiplyByFloats(t, t));
  2733. return Vector2.Distance(p, proj);
  2734. };
  2735. return Vector2;
  2736. }());
  2737. BABYLON.Vector2 = Vector2;
  2738. /**
  2739. * Classed used to store (x,y,z) vector representation
  2740. * A Vector3 is the main object used in 3D geometry
  2741. * It can represent etiher the coordinates of a point the space, either a direction
  2742. * Reminder: Babylon.js uses a left handed forward facing system
  2743. */
  2744. var Vector3 = /** @class */ (function () {
  2745. /**
  2746. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2747. * @param x defines the first coordinates (on X axis)
  2748. * @param y defines the second coordinates (on Y axis)
  2749. * @param z defines the third coordinates (on Z axis)
  2750. */
  2751. function Vector3(
  2752. /**
  2753. * Defines the first coordinates (on X axis)
  2754. */
  2755. x,
  2756. /**
  2757. * Defines the second coordinates (on Y axis)
  2758. */
  2759. y,
  2760. /**
  2761. * Defines the third coordinates (on Z axis)
  2762. */
  2763. z) {
  2764. if (x === void 0) { x = 0; }
  2765. if (y === void 0) { y = 0; }
  2766. if (z === void 0) { z = 0; }
  2767. this.x = x;
  2768. this.y = y;
  2769. this.z = z;
  2770. }
  2771. /**
  2772. * Creates a string representation of the Vector3
  2773. * @returns a string with the Vector3 coordinates.
  2774. */
  2775. Vector3.prototype.toString = function () {
  2776. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2777. };
  2778. /**
  2779. * Gets the class name
  2780. * @returns the string "Vector3"
  2781. */
  2782. Vector3.prototype.getClassName = function () {
  2783. return "Vector3";
  2784. };
  2785. /**
  2786. * Creates the Vector3 hash code
  2787. * @returns a number which tends to be unique between Vector3 instances
  2788. */
  2789. Vector3.prototype.getHashCode = function () {
  2790. var hash = this.x || 0;
  2791. hash = (hash * 397) ^ (this.y || 0);
  2792. hash = (hash * 397) ^ (this.z || 0);
  2793. return hash;
  2794. };
  2795. // Operators
  2796. /**
  2797. * Creates an array containing three elements : the coordinates of the Vector3
  2798. * @returns a new array of numbers
  2799. */
  2800. Vector3.prototype.asArray = function () {
  2801. var result = [];
  2802. this.toArray(result, 0);
  2803. return result;
  2804. };
  2805. /**
  2806. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2807. * @param array defines the destination array
  2808. * @param index defines the offset in the destination array
  2809. * @returns the current Vector3
  2810. */
  2811. Vector3.prototype.toArray = function (array, index) {
  2812. if (index === void 0) { index = 0; }
  2813. array[index] = this.x;
  2814. array[index + 1] = this.y;
  2815. array[index + 2] = this.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2820. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2821. */
  2822. Vector3.prototype.toQuaternion = function () {
  2823. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2824. };
  2825. /**
  2826. * Adds the given vector to the current Vector3
  2827. * @param otherVector defines the second operand
  2828. * @returns the current updated Vector3
  2829. */
  2830. Vector3.prototype.addInPlace = function (otherVector) {
  2831. this.x += otherVector.x;
  2832. this.y += otherVector.y;
  2833. this.z += otherVector.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2838. * @param otherVector defines the second operand
  2839. * @returns the resulting Vector3
  2840. */
  2841. Vector3.prototype.add = function (otherVector) {
  2842. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2843. };
  2844. /**
  2845. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2846. * @param otherVector defines the second operand
  2847. * @param result defines the Vector3 object where to store the result
  2848. * @returns the current Vector3
  2849. */
  2850. Vector3.prototype.addToRef = function (otherVector, result) {
  2851. result.x = this.x + otherVector.x;
  2852. result.y = this.y + otherVector.y;
  2853. result.z = this.z + otherVector.z;
  2854. return this;
  2855. };
  2856. /**
  2857. * Subtract the given vector from the current Vector3
  2858. * @param otherVector defines the second operand
  2859. * @returns the current updated Vector3
  2860. */
  2861. Vector3.prototype.subtractInPlace = function (otherVector) {
  2862. this.x -= otherVector.x;
  2863. this.y -= otherVector.y;
  2864. this.z -= otherVector.z;
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2869. * @param otherVector defines the second operand
  2870. * @returns the resulting Vector3
  2871. */
  2872. Vector3.prototype.subtract = function (otherVector) {
  2873. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2874. };
  2875. /**
  2876. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2877. * @param otherVector defines the second operand
  2878. * @param result defines the Vector3 object where to store the result
  2879. * @returns the current Vector3
  2880. */
  2881. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2882. result.x = this.x - otherVector.x;
  2883. result.y = this.y - otherVector.y;
  2884. result.z = this.z - otherVector.z;
  2885. return this;
  2886. };
  2887. /**
  2888. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2889. * @param x defines the x coordinate of the operand
  2890. * @param y defines the y coordinate of the operand
  2891. * @param z defines the z coordinate of the operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2895. return new Vector3(this.x - x, this.y - y, this.z - z);
  2896. };
  2897. /**
  2898. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2899. * @param x defines the x coordinate of the operand
  2900. * @param y defines the y coordinate of the operand
  2901. * @param z defines the z coordinate of the operand
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2906. result.x = this.x - x;
  2907. result.y = this.y - y;
  2908. result.z = this.z - z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2913. * @returns a new Vector3
  2914. */
  2915. Vector3.prototype.negate = function () {
  2916. return new Vector3(-this.x, -this.y, -this.z);
  2917. };
  2918. /**
  2919. * Multiplies the Vector3 coordinates by the float "scale"
  2920. * @param scale defines the multiplier factor
  2921. * @returns the current updated Vector3
  2922. */
  2923. Vector3.prototype.scaleInPlace = function (scale) {
  2924. this.x *= scale;
  2925. this.y *= scale;
  2926. this.z *= scale;
  2927. return this;
  2928. };
  2929. /**
  2930. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2931. * @param scale defines the multiplier factor
  2932. * @returns a new Vector3
  2933. */
  2934. Vector3.prototype.scale = function (scale) {
  2935. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2936. };
  2937. /**
  2938. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2939. * @param scale defines the multiplier factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the current Vector3
  2942. */
  2943. Vector3.prototype.scaleToRef = function (scale, result) {
  2944. result.x = this.x * scale;
  2945. result.y = this.y * scale;
  2946. result.z = this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2951. * @param scale defines the scale factor
  2952. * @param result defines the Vector3 object where to store the result
  2953. * @returns the unmodified current Vector3
  2954. */
  2955. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2956. result.x += this.x * scale;
  2957. result.y += this.y * scale;
  2958. result.z += this.z * scale;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2963. * @param otherVector defines the second operand
  2964. * @returns true if both vectors are equals
  2965. */
  2966. Vector3.prototype.equals = function (otherVector) {
  2967. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2968. };
  2969. /**
  2970. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2971. * @param otherVector defines the second operand
  2972. * @param epsilon defines the minimal distance to define values as equals
  2973. * @returns true if both vectors are distant less than epsilon
  2974. */
  2975. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2976. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2977. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 coordinates equals the given floats
  2981. * @param x defines the x coordinate of the operand
  2982. * @param y defines the y coordinate of the operand
  2983. * @param z defines the z coordinate of the operand
  2984. * @returns true if both vectors are equals
  2985. */
  2986. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2987. return this.x === x && this.y === y && this.z === z;
  2988. };
  2989. /**
  2990. * Multiplies the current Vector3 coordinates by the given ones
  2991. * @param otherVector defines the second operand
  2992. * @returns the current updated Vector3
  2993. */
  2994. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2995. this.x *= otherVector.x;
  2996. this.y *= otherVector.y;
  2997. this.z *= otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3002. * @param otherVector defines the second operand
  3003. * @returns the new Vector3
  3004. */
  3005. Vector3.prototype.multiply = function (otherVector) {
  3006. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3007. };
  3008. /**
  3009. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3010. * @param otherVector defines the second operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3015. result.x = this.x * otherVector.x;
  3016. result.y = this.y * otherVector.y;
  3017. result.z = this.z * otherVector.z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3028. return new Vector3(this.x * x, this.y * y, this.z * z);
  3029. };
  3030. /**
  3031. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3032. * @param otherVector defines the second operand
  3033. * @returns the new Vector3
  3034. */
  3035. Vector3.prototype.divide = function (otherVector) {
  3036. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3040. * @param otherVector defines the second operand
  3041. * @param result defines the Vector3 object where to store the result
  3042. * @returns the current Vector3
  3043. */
  3044. Vector3.prototype.divideToRef = function (otherVector, result) {
  3045. result.x = this.x / otherVector.x;
  3046. result.y = this.y / otherVector.y;
  3047. result.z = this.z / otherVector.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Divides the current Vector3 coordinates by the given ones.
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.divideInPlace = function (otherVector) {
  3056. return this.divideToRef(otherVector, this);
  3057. };
  3058. /**
  3059. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3060. * @param other defines the second operand
  3061. * @returns the current updated Vector3
  3062. */
  3063. Vector3.prototype.minimizeInPlace = function (other) {
  3064. if (other.x < this.x)
  3065. this.x = other.x;
  3066. if (other.y < this.y)
  3067. this.y = other.y;
  3068. if (other.z < this.z)
  3069. this.z = other.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3074. * @param other defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.maximizeInPlace = function (other) {
  3078. if (other.x > this.x)
  3079. this.x = other.x;
  3080. if (other.y > this.y)
  3081. this.y = other.y;
  3082. if (other.z > this.z)
  3083. this.z = other.z;
  3084. return this;
  3085. };
  3086. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3087. /**
  3088. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3089. */
  3090. get: function () {
  3091. var absX = Math.abs(this.x);
  3092. var absY = Math.abs(this.y);
  3093. if (absX !== absY) {
  3094. return true;
  3095. }
  3096. var absZ = Math.abs(this.z);
  3097. if (absX !== absZ) {
  3098. return true;
  3099. }
  3100. if (absY !== absZ) {
  3101. return true;
  3102. }
  3103. return false;
  3104. },
  3105. enumerable: true,
  3106. configurable: true
  3107. });
  3108. // Properties
  3109. /**
  3110. * Gets the length of the Vector3
  3111. * @returns the length of the Vecto3
  3112. */
  3113. Vector3.prototype.length = function () {
  3114. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3115. };
  3116. /**
  3117. * Gets the squared length of the Vector3
  3118. * @returns squared length of the Vector3
  3119. */
  3120. Vector3.prototype.lengthSquared = function () {
  3121. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3122. };
  3123. /**
  3124. * Normalize the current Vector3.
  3125. * Please note that this is an in place operation.
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.normalize = function () {
  3129. var len = this.length();
  3130. if (len === 0 || len === 1.0)
  3131. return this;
  3132. var num = 1.0 / len;
  3133. this.x *= num;
  3134. this.y *= num;
  3135. this.z *= num;
  3136. return this;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to a new vector
  3140. * @returns the new Vector3
  3141. */
  3142. Vector3.prototype.normalizeToNew = function () {
  3143. var normalized = new Vector3(0, 0, 0);
  3144. this.normalizeToRef(normalized);
  3145. return normalized;
  3146. };
  3147. /**
  3148. * Normalize the current Vector3 to the reference
  3149. * @param reference define the Vector3 to update
  3150. * @returns the updated Vector3
  3151. */
  3152. Vector3.prototype.normalizeToRef = function (reference) {
  3153. var len = this.length();
  3154. if (len === 0 || len === 1.0) {
  3155. reference.set(this.x, this.y, this.z);
  3156. return reference;
  3157. }
  3158. var scale = 1.0 / len;
  3159. this.scaleToRef(scale, reference);
  3160. return reference;
  3161. };
  3162. /**
  3163. * Creates a new Vector3 copied from the current Vector3
  3164. * @returns the new Vector3
  3165. */
  3166. Vector3.prototype.clone = function () {
  3167. return new Vector3(this.x, this.y, this.z);
  3168. };
  3169. /**
  3170. * Copies the given vector coordinates to the current Vector3 ones
  3171. * @param source defines the source Vector3
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.copyFrom = function (source) {
  3175. this.x = source.x;
  3176. this.y = source.y;
  3177. this.z = source.z;
  3178. return this;
  3179. };
  3180. /**
  3181. * Copies the given floats to the current Vector3 coordinates
  3182. * @param x defines the x coordinate of the operand
  3183. * @param y defines the y coordinate of the operand
  3184. * @param z defines the z coordinate of the operand
  3185. * @returns the current updated Vector3
  3186. */
  3187. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3188. this.x = x;
  3189. this.y = y;
  3190. this.z = z;
  3191. return this;
  3192. };
  3193. /**
  3194. * Copies the given floats to the current Vector3 coordinates
  3195. * @param x defines the x coordinate of the operand
  3196. * @param y defines the y coordinate of the operand
  3197. * @param z defines the z coordinate of the operand
  3198. * @returns the current updated Vector3
  3199. */
  3200. Vector3.prototype.set = function (x, y, z) {
  3201. return this.copyFromFloats(x, y, z);
  3202. };
  3203. // Statics
  3204. /**
  3205. * Get the clip factor between two vectors
  3206. * @param vector0 defines the first operand
  3207. * @param vector1 defines the second operand
  3208. * @param axis defines the axis to use
  3209. * @param size defines the size along the axis
  3210. * @returns the clip factor
  3211. */
  3212. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3213. var d0 = Vector3.Dot(vector0, axis) - size;
  3214. var d1 = Vector3.Dot(vector1, axis) - size;
  3215. var s = d0 / (d0 - d1);
  3216. return s;
  3217. };
  3218. /**
  3219. * Get angle between two vectors
  3220. * @param vector0 angle between vector0 and vector1
  3221. * @param vector1 angle between vector0 and vector1
  3222. * @param normal direction of the normal
  3223. * @return the angle between vector0 and vector1
  3224. */
  3225. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3226. var v0 = vector0.clone().normalize();
  3227. var v1 = vector1.clone().normalize();
  3228. var dot = Vector3.Dot(v0, v1);
  3229. var n = Vector3.Cross(v0, v1);
  3230. if (Vector3.Dot(n, normal) > 0) {
  3231. return Math.acos(dot);
  3232. }
  3233. return -Math.acos(dot);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given array
  3237. * @param array defines the source array
  3238. * @param offset defines the offset in the source array
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.FromArray = function (array, offset) {
  3242. if (!offset) {
  3243. offset = 0;
  3244. }
  3245. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3249. * This function is deprecated. Use FromArray instead
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @returns the new Vector3
  3253. */
  3254. Vector3.FromFloatArray = function (array, offset) {
  3255. return Vector3.FromArray(array, offset);
  3256. };
  3257. /**
  3258. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromArrayToRef = function (array, offset, result) {
  3264. result.x = array[offset];
  3265. result.y = array[offset + 1];
  3266. result.z = array[offset + 2];
  3267. };
  3268. /**
  3269. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3270. * This function is deprecated. Use FromArrayToRef instead.
  3271. * @param array defines the source array
  3272. * @param offset defines the offset in the source array
  3273. * @param result defines the Vector3 where to store the result
  3274. */
  3275. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3276. return Vector3.FromArrayToRef(array, offset, result);
  3277. };
  3278. /**
  3279. * Sets the given vector "result" with the given floats.
  3280. * @param x defines the x coordinate of the source
  3281. * @param y defines the y coordinate of the source
  3282. * @param z defines the z coordinate of the source
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3286. result.x = x;
  3287. result.y = y;
  3288. result.z = z;
  3289. };
  3290. /**
  3291. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3292. * @returns a new empty Vector3
  3293. */
  3294. Vector3.Zero = function () {
  3295. return new Vector3(0.0, 0.0, 0.0);
  3296. };
  3297. /**
  3298. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3299. * @returns a new unit Vector3
  3300. */
  3301. Vector3.One = function () {
  3302. return new Vector3(1.0, 1.0, 1.0);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3306. * @returns a new up Vector3
  3307. */
  3308. Vector3.Up = function () {
  3309. return new Vector3(0.0, 1.0, 0.0);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3313. * @returns a new down Vector3
  3314. */
  3315. Vector3.Down = function () {
  3316. return new Vector3(0.0, -1.0, 0.0);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3320. * @returns a new forward Vector3
  3321. */
  3322. Vector3.Forward = function () {
  3323. return new Vector3(0.0, 0.0, 1.0);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3327. * @returns a new right Vector3
  3328. */
  3329. Vector3.Right = function () {
  3330. return new Vector3(1.0, 0.0, 0.0);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3334. * @returns a new left Vector3
  3335. */
  3336. Vector3.Left = function () {
  3337. return new Vector3(-1.0, 0.0, 0.0);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @returns the transformed Vector3
  3345. */
  3346. Vector3.TransformCoordinates = function (vector, transformation) {
  3347. var result = Vector3.Zero();
  3348. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3349. return result;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3353. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3354. * @param vector defines the Vector3 to transform
  3355. * @param transformation defines the transformation matrix
  3356. * @param result defines the Vector3 where to store the result
  3357. */
  3358. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3359. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3360. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3361. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3362. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3363. result.x = x / w;
  3364. result.y = y / w;
  3365. result.z = z / w;
  3366. };
  3367. /**
  3368. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3369. * This method computes tranformed coordinates only, not transformed direction vectors
  3370. * @param x define the x coordinate of the source vector
  3371. * @param y define the y coordinate of the source vector
  3372. * @param z define the z coordinate of the source vector
  3373. * @param transformation defines the transformation matrix
  3374. * @param result defines the Vector3 where to store the result
  3375. */
  3376. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3377. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3378. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3379. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3380. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3381. result.x = rx / rw;
  3382. result.y = ry / rw;
  3383. result.z = rz / rw;
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.TransformNormal = function (vector, transformation) {
  3393. var result = Vector3.Zero();
  3394. Vector3.TransformNormalToRef(vector, transformation, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param vector defines the Vector3 to transform
  3401. * @param transformation defines the transformation matrix
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3408. result.x = x;
  3409. result.y = y;
  3410. result.z = z;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param x define the x coordinate of the source vector
  3416. * @param y define the y coordinate of the source vector
  3417. * @param z define the z coordinate of the source vector
  3418. * @param transformation defines the transformation matrix
  3419. * @param result defines the Vector3 where to store the result
  3420. */
  3421. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3422. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3423. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3424. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3428. * @param value1 defines the first control point
  3429. * @param value2 defines the second control point
  3430. * @param value3 defines the third control point
  3431. * @param value4 defines the fourth control point
  3432. * @param amount defines the amount on the spline to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3436. var squared = amount * amount;
  3437. var cubed = amount * squared;
  3438. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3439. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3440. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3441. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3442. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3443. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3444. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3445. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3446. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3447. return new Vector3(x, y, z);
  3448. };
  3449. /**
  3450. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3451. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3452. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3453. * @param value defines the current value
  3454. * @param min defines the lower range value
  3455. * @param max defines the upper range value
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Clamp = function (value, min, max) {
  3459. var x = value.x;
  3460. x = (x > max.x) ? max.x : x;
  3461. x = (x < min.x) ? min.x : x;
  3462. var y = value.y;
  3463. y = (y > max.y) ? max.y : y;
  3464. y = (y < min.y) ? min.y : y;
  3465. var z = value.z;
  3466. z = (z > max.z) ? max.z : z;
  3467. z = (z < min.z) ? min.z : z;
  3468. return new Vector3(x, y, z);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3472. * @param value1 defines the first control point
  3473. * @param tangent1 defines the first tangent vector
  3474. * @param value2 defines the second control point
  3475. * @param tangent2 defines the second tangent vector
  3476. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3480. var squared = amount * amount;
  3481. var cubed = amount * squared;
  3482. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3483. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3484. var part3 = (cubed - (2.0 * squared)) + amount;
  3485. var part4 = cubed - squared;
  3486. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3487. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3488. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3489. return new Vector3(x, y, z);
  3490. };
  3491. /**
  3492. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @returns the new Vector3
  3497. */
  3498. Vector3.Lerp = function (start, end, amount) {
  3499. var result = new Vector3(0, 0, 0);
  3500. Vector3.LerpToRef(start, end, amount, result);
  3501. return result;
  3502. };
  3503. /**
  3504. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3505. * @param start defines the start value
  3506. * @param end defines the end value
  3507. * @param amount max defines amount between both (between 0 and 1)
  3508. * @param result defines the Vector3 where to store the result
  3509. */
  3510. Vector3.LerpToRef = function (start, end, amount, result) {
  3511. result.x = start.x + ((end.x - start.x) * amount);
  3512. result.y = start.y + ((end.y - start.y) * amount);
  3513. result.z = start.z + ((end.z - start.z) * amount);
  3514. };
  3515. /**
  3516. * Returns the dot product (float) between the vectors "left" and "right"
  3517. * @param left defines the left operand
  3518. * @param right defines the right operand
  3519. * @returns the dot product
  3520. */
  3521. Vector3.Dot = function (left, right) {
  3522. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @returns the cross product
  3530. */
  3531. Vector3.Cross = function (left, right) {
  3532. var result = Vector3.Zero();
  3533. Vector3.CrossToRef(left, right, result);
  3534. return result;
  3535. };
  3536. /**
  3537. * Sets the given vector "result" with the cross product of "left" and "right"
  3538. * The cross product is then orthogonal to both "left" and "right"
  3539. * @param left defines the left operand
  3540. * @param right defines the right operand
  3541. * @param result defines the Vector3 where to store the result
  3542. */
  3543. Vector3.CrossToRef = function (left, right, result) {
  3544. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3545. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3546. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3547. result.copyFrom(MathTmp.Vector3[0]);
  3548. };
  3549. /**
  3550. * Returns a new Vector3 as the normalization of the given vector
  3551. * @param vector defines the Vector3 to normalize
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Normalize = function (vector) {
  3555. var result = Vector3.Zero();
  3556. Vector3.NormalizeToRef(vector, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the given vector "result" with the normalization of the given first vector
  3561. * @param vector defines the Vector3 to normalize
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.NormalizeToRef = function (vector, result) {
  3565. result.copyFrom(vector);
  3566. result.normalize();
  3567. };
  3568. /**
  3569. * Project a Vector3 onto screen space
  3570. * @param vector defines the Vector3 to project
  3571. * @param world defines the world matrix to use
  3572. * @param transform defines the transform (view x projection) matrix to use
  3573. * @param viewport defines the screen viewport to use
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Project = function (vector, world, transform, viewport) {
  3577. var cw = viewport.width;
  3578. var ch = viewport.height;
  3579. var cx = viewport.x;
  3580. var cy = viewport.y;
  3581. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3582. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(transform, matrix);
  3585. matrix.multiplyToRef(viewportMatrix, matrix);
  3586. return Vector3.TransformCoordinates(vector, matrix);
  3587. };
  3588. /**
  3589. * Unproject from screen space to object space
  3590. * @param source defines the screen space Vector3 to use
  3591. * @param viewportWidth defines the current width of the viewport
  3592. * @param viewportHeight defines the current height of the viewport
  3593. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3594. * @param transform defines the transform (view x projection) matrix to use
  3595. * @returns the new Vector3
  3596. */
  3597. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.invert();
  3601. source.x = source.x / viewportWidth * 2 - 1;
  3602. source.y = -(source.y / viewportHeight * 2 - 1);
  3603. var vector = Vector3.TransformCoordinates(source, matrix);
  3604. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3605. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3606. vector = vector.scale(1.0 / num);
  3607. }
  3608. return vector;
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param view defines the view matrix to use
  3617. * @param projection defines the projection matrix to use
  3618. * @returns the new Vector3
  3619. */
  3620. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3621. var result = Vector3.Zero();
  3622. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3623. return result;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @param result defines the Vector3 where to store the result
  3634. */
  3635. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3636. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3637. };
  3638. /**
  3639. * Unproject from screen space to object space
  3640. * @param sourceX defines the screen space x coordinate to use
  3641. * @param sourceY defines the screen space y coordinate to use
  3642. * @param sourceZ defines the screen space z coordinate to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. var matrix = MathTmp.Matrix[0];
  3652. world.multiplyToRef(view, matrix);
  3653. matrix.multiplyToRef(projection, matrix);
  3654. matrix.invert();
  3655. var screenSource = MathTmp.Vector3[0];
  3656. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3657. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3658. screenSource.z = 2 * sourceZ - 1.0;
  3659. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3660. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3661. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3662. result.scaleInPlace(1.0 / num);
  3663. }
  3664. };
  3665. /**
  3666. * Gets the minimal coordinate values between two Vector3
  3667. * @param left defines the first operand
  3668. * @param right defines the second operand
  3669. * @returns the new Vector3
  3670. */
  3671. Vector3.Minimize = function (left, right) {
  3672. var min = left.clone();
  3673. min.minimizeInPlace(right);
  3674. return min;
  3675. };
  3676. /**
  3677. * Gets the maximal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Maximize = function (left, right) {
  3683. var max = left.clone();
  3684. max.maximizeInPlace(right);
  3685. return max;
  3686. };
  3687. /**
  3688. * Returns the distance between the vectors "value1" and "value2"
  3689. * @param value1 defines the first operand
  3690. * @param value2 defines the second operand
  3691. * @returns the distance
  3692. */
  3693. Vector3.Distance = function (value1, value2) {
  3694. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3695. };
  3696. /**
  3697. * Returns the squared distance between the vectors "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the squared distance
  3701. */
  3702. Vector3.DistanceSquared = function (value1, value2) {
  3703. var x = value1.x - value2.x;
  3704. var y = value1.y - value2.y;
  3705. var z = value1.z - value2.z;
  3706. return (x * x) + (y * y) + (z * z);
  3707. };
  3708. /**
  3709. * Returns a new Vector3 located at the center between "value1" and "value2"
  3710. * @param value1 defines the first operand
  3711. * @param value2 defines the second operand
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Center = function (value1, value2) {
  3715. var center = value1.add(value2);
  3716. center.scaleInPlace(0.5);
  3717. return center;
  3718. };
  3719. /**
  3720. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3721. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3722. * to something in order to rotate it from its local system to the given target system
  3723. * Note: axis1, axis2 and axis3 are normalized during this operation
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @returns a new Vector3
  3728. */
  3729. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3730. var rotation = Vector3.Zero();
  3731. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3732. return rotation;
  3733. };
  3734. /**
  3735. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3736. * @param axis1 defines the first axis
  3737. * @param axis2 defines the second axis
  3738. * @param axis3 defines the third axis
  3739. * @param ref defines the Vector3 where to store the result
  3740. */
  3741. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3742. var quat = MathTmp.Quaternion[0];
  3743. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3744. quat.toEulerAnglesToRef(ref);
  3745. };
  3746. return Vector3;
  3747. }());
  3748. BABYLON.Vector3 = Vector3;
  3749. //Vector4 class created for EulerAngle class conversion to Quaternion
  3750. var Vector4 = /** @class */ (function () {
  3751. /**
  3752. * Creates a Vector4 object from the given floats.
  3753. */
  3754. function Vector4(x, y, z, w) {
  3755. this.x = x;
  3756. this.y = y;
  3757. this.z = z;
  3758. this.w = w;
  3759. }
  3760. /**
  3761. * Returns the string with the Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.toString = function () {
  3764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3765. };
  3766. /**
  3767. * Returns the string "Vector4".
  3768. */
  3769. Vector4.prototype.getClassName = function () {
  3770. return "Vector4";
  3771. };
  3772. /**
  3773. * Returns the Vector4 hash code.
  3774. */
  3775. Vector4.prototype.getHashCode = function () {
  3776. var hash = this.x || 0;
  3777. hash = (hash * 397) ^ (this.y || 0);
  3778. hash = (hash * 397) ^ (this.z || 0);
  3779. hash = (hash * 397) ^ (this.w || 0);
  3780. return hash;
  3781. };
  3782. // Operators
  3783. /**
  3784. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.asArray = function () {
  3787. var result = new Array();
  3788. this.toArray(result, 0);
  3789. return result;
  3790. };
  3791. /**
  3792. * Populates the given array from the given index with the Vector4 coordinates.
  3793. * Returns the Vector4.
  3794. */
  3795. Vector4.prototype.toArray = function (array, index) {
  3796. if (index === undefined) {
  3797. index = 0;
  3798. }
  3799. array[index] = this.x;
  3800. array[index + 1] = this.y;
  3801. array[index + 2] = this.z;
  3802. array[index + 3] = this.w;
  3803. return this;
  3804. };
  3805. /**
  3806. * Adds the given vector to the current Vector4.
  3807. * Returns the updated Vector4.
  3808. */
  3809. Vector4.prototype.addInPlace = function (otherVector) {
  3810. this.x += otherVector.x;
  3811. this.y += otherVector.y;
  3812. this.z += otherVector.z;
  3813. this.w += otherVector.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3818. */
  3819. Vector4.prototype.add = function (otherVector) {
  3820. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3821. };
  3822. /**
  3823. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3824. * Returns the current Vector4.
  3825. */
  3826. Vector4.prototype.addToRef = function (otherVector, result) {
  3827. result.x = this.x + otherVector.x;
  3828. result.y = this.y + otherVector.y;
  3829. result.z = this.z + otherVector.z;
  3830. result.w = this.w + otherVector.w;
  3831. return this;
  3832. };
  3833. /**
  3834. * Subtract in place the given vector from the current Vector4.
  3835. * Returns the updated Vector4.
  3836. */
  3837. Vector4.prototype.subtractInPlace = function (otherVector) {
  3838. this.x -= otherVector.x;
  3839. this.y -= otherVector.y;
  3840. this.z -= otherVector.z;
  3841. this.w -= otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3846. */
  3847. Vector4.prototype.subtract = function (otherVector) {
  3848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3849. };
  3850. /**
  3851. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3852. * Returns the current Vector4.
  3853. */
  3854. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3855. result.x = this.x - otherVector.x;
  3856. result.y = this.y - otherVector.y;
  3857. result.z = this.z - otherVector.z;
  3858. result.w = this.w - otherVector.w;
  3859. return this;
  3860. };
  3861. /**
  3862. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3865. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3866. };
  3867. /**
  3868. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3869. * Returns the current Vector4.
  3870. */
  3871. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3872. result.x = this.x - x;
  3873. result.y = this.y - y;
  3874. result.z = this.z - z;
  3875. result.w = this.w - w;
  3876. return this;
  3877. };
  3878. /**
  3879. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3880. */
  3881. Vector4.prototype.negate = function () {
  3882. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3883. };
  3884. /**
  3885. * Multiplies the current Vector4 coordinates by scale (float).
  3886. * Returns the updated Vector4.
  3887. */
  3888. Vector4.prototype.scaleInPlace = function (scale) {
  3889. this.x *= scale;
  3890. this.y *= scale;
  3891. this.z *= scale;
  3892. this.w *= scale;
  3893. return this;
  3894. };
  3895. /**
  3896. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3897. */
  3898. Vector4.prototype.scale = function (scale) {
  3899. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3900. };
  3901. /**
  3902. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3903. * Returns the current Vector4.
  3904. */
  3905. Vector4.prototype.scaleToRef = function (scale, result) {
  3906. result.x = this.x * scale;
  3907. result.y = this.y * scale;
  3908. result.z = this.z * scale;
  3909. result.w = this.w * scale;
  3910. return this;
  3911. };
  3912. /**
  3913. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3914. * @param scale defines the scale factor
  3915. * @param result defines the Vector4 object where to store the result
  3916. * @returns the unmodified current Vector4
  3917. */
  3918. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3919. result.x += this.x * scale;
  3920. result.y += this.y * scale;
  3921. result.z += this.z * scale;
  3922. result.w += this.w * scale;
  3923. return this;
  3924. };
  3925. /**
  3926. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3927. */
  3928. Vector4.prototype.equals = function (otherVector) {
  3929. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3930. };
  3931. /**
  3932. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3933. */
  3934. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3935. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3936. return otherVector
  3937. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3938. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3939. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3940. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3941. };
  3942. /**
  3943. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3946. return this.x === x && this.y === y && this.z === z && this.w === w;
  3947. };
  3948. /**
  3949. * Multiplies in place the current Vector4 by the given one.
  3950. * Returns the updated Vector4.
  3951. */
  3952. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3953. this.x *= otherVector.x;
  3954. this.y *= otherVector.y;
  3955. this.z *= otherVector.z;
  3956. this.w *= otherVector.w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3961. */
  3962. Vector4.prototype.multiply = function (otherVector) {
  3963. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3964. };
  3965. /**
  3966. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3967. * Returns the current Vector4.
  3968. */
  3969. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3970. result.x = this.x * otherVector.x;
  3971. result.y = this.y * otherVector.y;
  3972. result.z = this.z * otherVector.z;
  3973. result.w = this.w * otherVector.w;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3978. */
  3979. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3980. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3984. */
  3985. Vector4.prototype.divide = function (otherVector) {
  3986. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3987. };
  3988. /**
  3989. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3990. * Returns the current Vector4.
  3991. */
  3992. Vector4.prototype.divideToRef = function (otherVector, result) {
  3993. result.x = this.x / otherVector.x;
  3994. result.y = this.y / otherVector.y;
  3995. result.z = this.z / otherVector.z;
  3996. result.w = this.w / otherVector.w;
  3997. return this;
  3998. };
  3999. /**
  4000. * Divides the current Vector3 coordinates by the given ones.
  4001. * @returns the updated Vector3.
  4002. */
  4003. Vector4.prototype.divideInPlace = function (otherVector) {
  4004. return this.divideToRef(otherVector, this);
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.minimizeInPlace = function (other) {
  4012. if (other.x < this.x)
  4013. this.x = other.x;
  4014. if (other.y < this.y)
  4015. this.y = other.y;
  4016. if (other.z < this.z)
  4017. this.z = other.z;
  4018. if (other.w < this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4024. * @param other defines the second operand
  4025. * @returns the current updated Vector4
  4026. */
  4027. Vector4.prototype.maximizeInPlace = function (other) {
  4028. if (other.x > this.x)
  4029. this.x = other.x;
  4030. if (other.y > this.y)
  4031. this.y = other.y;
  4032. if (other.z > this.z)
  4033. this.z = other.z;
  4034. if (other.w > this.w)
  4035. this.w = other.w;
  4036. return this;
  4037. };
  4038. // Properties
  4039. /**
  4040. * Returns the Vector4 length (float).
  4041. */
  4042. Vector4.prototype.length = function () {
  4043. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4044. };
  4045. /**
  4046. * Returns the Vector4 squared length (float).
  4047. */
  4048. Vector4.prototype.lengthSquared = function () {
  4049. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4050. };
  4051. // Methods
  4052. /**
  4053. * Normalizes in place the Vector4.
  4054. * Returns the updated Vector4.
  4055. */
  4056. Vector4.prototype.normalize = function () {
  4057. var len = this.length();
  4058. if (len === 0)
  4059. return this;
  4060. var num = 1.0 / len;
  4061. this.x *= num;
  4062. this.y *= num;
  4063. this.z *= num;
  4064. this.w *= num;
  4065. return this;
  4066. };
  4067. /**
  4068. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4069. */
  4070. Vector4.prototype.toVector3 = function () {
  4071. return new Vector3(this.x, this.y, this.z);
  4072. };
  4073. /**
  4074. * Returns a new Vector4 copied from the current one.
  4075. */
  4076. Vector4.prototype.clone = function () {
  4077. return new Vector4(this.x, this.y, this.z, this.w);
  4078. };
  4079. /**
  4080. * Updates the current Vector4 with the given one coordinates.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.copyFrom = function (source) {
  4084. this.x = source.x;
  4085. this.y = source.y;
  4086. this.z = source.z;
  4087. this.w = source.w;
  4088. return this;
  4089. };
  4090. /**
  4091. * Updates the current Vector4 coordinates with the given floats.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4095. this.x = x;
  4096. this.y = y;
  4097. this.z = z;
  4098. this.w = w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.set = function (x, y, z, w) {
  4106. return this.copyFromFloats(x, y, z, w);
  4107. };
  4108. // Statics
  4109. /**
  4110. * Returns a new Vector4 set from the starting index of the given array.
  4111. */
  4112. Vector4.FromArray = function (array, offset) {
  4113. if (!offset) {
  4114. offset = 0;
  4115. }
  4116. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4117. };
  4118. /**
  4119. * Updates the given vector "result" from the starting index of the given array.
  4120. */
  4121. Vector4.FromArrayToRef = function (array, offset, result) {
  4122. result.x = array[offset];
  4123. result.y = array[offset + 1];
  4124. result.z = array[offset + 2];
  4125. result.w = array[offset + 3];
  4126. };
  4127. /**
  4128. * Updates the given vector "result" from the starting index of the given Float32Array.
  4129. */
  4130. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4131. Vector4.FromArrayToRef(array, offset, result);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" coordinates from the given floats.
  4135. */
  4136. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4137. result.x = x;
  4138. result.y = y;
  4139. result.z = z;
  4140. result.w = w;
  4141. };
  4142. /**
  4143. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4144. */
  4145. Vector4.Zero = function () {
  4146. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4147. };
  4148. /**
  4149. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4150. */
  4151. Vector4.One = function () {
  4152. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4153. };
  4154. /**
  4155. * Returns a new normalized Vector4 from the given one.
  4156. */
  4157. Vector4.Normalize = function (vector) {
  4158. var result = Vector4.Zero();
  4159. Vector4.NormalizeToRef(vector, result);
  4160. return result;
  4161. };
  4162. /**
  4163. * Updates the given vector "result" from the normalization of the given one.
  4164. */
  4165. Vector4.NormalizeToRef = function (vector, result) {
  4166. result.copyFrom(vector);
  4167. result.normalize();
  4168. };
  4169. Vector4.Minimize = function (left, right) {
  4170. var min = left.clone();
  4171. min.minimizeInPlace(right);
  4172. return min;
  4173. };
  4174. Vector4.Maximize = function (left, right) {
  4175. var max = left.clone();
  4176. max.maximizeInPlace(right);
  4177. return max;
  4178. };
  4179. /**
  4180. * Returns the distance (float) between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Distance = function (value1, value2) {
  4183. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4184. };
  4185. /**
  4186. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4187. */
  4188. Vector4.DistanceSquared = function (value1, value2) {
  4189. var x = value1.x - value2.x;
  4190. var y = value1.y - value2.y;
  4191. var z = value1.z - value2.z;
  4192. var w = value1.w - value2.w;
  4193. return (x * x) + (y * y) + (z * z) + (w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4197. */
  4198. Vector4.Center = function (value1, value2) {
  4199. var center = value1.add(value2);
  4200. center.scaleInPlace(0.5);
  4201. return center;
  4202. };
  4203. /**
  4204. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4205. * This methods computes transformed normalized direction vectors only.
  4206. */
  4207. Vector4.TransformNormal = function (vector, transformation) {
  4208. var result = Vector4.Zero();
  4209. Vector4.TransformNormalToRef(vector, transformation, result);
  4210. return result;
  4211. };
  4212. /**
  4213. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4214. * This methods computes transformed normalized direction vectors only.
  4215. */
  4216. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4217. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4218. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4219. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4220. result.x = x;
  4221. result.y = y;
  4222. result.z = z;
  4223. result.w = vector.w;
  4224. };
  4225. /**
  4226. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4227. * This methods computes transformed normalized direction vectors only.
  4228. */
  4229. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4230. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4231. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4232. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4233. result.w = w;
  4234. };
  4235. return Vector4;
  4236. }());
  4237. BABYLON.Vector4 = Vector4;
  4238. var Size = /** @class */ (function () {
  4239. /**
  4240. * Creates a Size object from the given width and height (floats).
  4241. */
  4242. function Size(width, height) {
  4243. this.width = width;
  4244. this.height = height;
  4245. }
  4246. // Returns a string with the Size width and height.
  4247. Size.prototype.toString = function () {
  4248. return "{W: " + this.width + ", H: " + this.height + "}";
  4249. };
  4250. /**
  4251. * Returns the string "Size"
  4252. */
  4253. Size.prototype.getClassName = function () {
  4254. return "Size";
  4255. };
  4256. /**
  4257. * Returns the Size hash code.
  4258. */
  4259. Size.prototype.getHashCode = function () {
  4260. var hash = this.width || 0;
  4261. hash = (hash * 397) ^ (this.height || 0);
  4262. return hash;
  4263. };
  4264. /**
  4265. * Updates the current size from the given one.
  4266. * Returns the updated Size.
  4267. */
  4268. Size.prototype.copyFrom = function (src) {
  4269. this.width = src.width;
  4270. this.height = src.height;
  4271. };
  4272. /**
  4273. * Updates in place the current Size from the given floats.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFromFloats = function (width, height) {
  4277. this.width = width;
  4278. this.height = height;
  4279. return this;
  4280. };
  4281. /**
  4282. * Updates in place the current Size from the given floats.
  4283. * Returns the updated Size.
  4284. */
  4285. Size.prototype.set = function (width, height) {
  4286. return this.copyFromFloats(width, height);
  4287. };
  4288. /**
  4289. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4290. */
  4291. Size.prototype.multiplyByFloats = function (w, h) {
  4292. return new Size(this.width * w, this.height * h);
  4293. };
  4294. /**
  4295. * Returns a new Size copied from the given one.
  4296. */
  4297. Size.prototype.clone = function () {
  4298. return new Size(this.width, this.height);
  4299. };
  4300. /**
  4301. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4302. */
  4303. Size.prototype.equals = function (other) {
  4304. if (!other) {
  4305. return false;
  4306. }
  4307. return (this.width === other.width) && (this.height === other.height);
  4308. };
  4309. Object.defineProperty(Size.prototype, "surface", {
  4310. /**
  4311. * Returns the surface of the Size : width * height (float).
  4312. */
  4313. get: function () {
  4314. return this.width * this.height;
  4315. },
  4316. enumerable: true,
  4317. configurable: true
  4318. });
  4319. /**
  4320. * Returns a new Size set to (0.0, 0.0)
  4321. */
  4322. Size.Zero = function () {
  4323. return new Size(0.0, 0.0);
  4324. };
  4325. /**
  4326. * Returns a new Size set as the addition result of the current Size and the given one.
  4327. */
  4328. Size.prototype.add = function (otherSize) {
  4329. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4330. return r;
  4331. };
  4332. /**
  4333. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4334. */
  4335. Size.prototype.subtract = function (otherSize) {
  4336. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4337. return r;
  4338. };
  4339. /**
  4340. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4341. */
  4342. Size.Lerp = function (start, end, amount) {
  4343. var w = start.width + ((end.width - start.width) * amount);
  4344. var h = start.height + ((end.height - start.height) * amount);
  4345. return new Size(w, h);
  4346. };
  4347. return Size;
  4348. }());
  4349. BABYLON.Size = Size;
  4350. /**
  4351. * Class used to store quaternion data
  4352. * @see https://en.wikipedia.org/wiki/Quaternion
  4353. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4354. */
  4355. var Quaternion = /** @class */ (function () {
  4356. /**
  4357. * Creates a new Quaternion from the given floats
  4358. * @param x defines the first component (0 by default)
  4359. * @param y defines the second component (0 by default)
  4360. * @param z defines the third component (0 by default)
  4361. * @param w defines the fourth component (1.0 by default)
  4362. */
  4363. function Quaternion(
  4364. /** defines the first component (0 by default) */
  4365. x,
  4366. /** defines the second component (0 by default) */
  4367. y,
  4368. /** defines the third component (0 by default) */
  4369. z,
  4370. /** defines the fourth component (1.0 by default) */
  4371. w) {
  4372. if (x === void 0) { x = 0.0; }
  4373. if (y === void 0) { y = 0.0; }
  4374. if (z === void 0) { z = 0.0; }
  4375. if (w === void 0) { w = 1.0; }
  4376. this.x = x;
  4377. this.y = y;
  4378. this.z = z;
  4379. this.w = w;
  4380. }
  4381. /**
  4382. * Gets a string representation for the current quaternion
  4383. * @returns a string with the Quaternion coordinates
  4384. */
  4385. Quaternion.prototype.toString = function () {
  4386. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4387. };
  4388. /**
  4389. * Gets the class name of the quaternion
  4390. * @returns the string "Quaternion"
  4391. */
  4392. Quaternion.prototype.getClassName = function () {
  4393. return "Quaternion";
  4394. };
  4395. /**
  4396. * Gets a hash code for this quaternion
  4397. * @returns the quaternion hash code
  4398. */
  4399. Quaternion.prototype.getHashCode = function () {
  4400. var hash = this.x || 0;
  4401. hash = (hash * 397) ^ (this.y || 0);
  4402. hash = (hash * 397) ^ (this.z || 0);
  4403. hash = (hash * 397) ^ (this.w || 0);
  4404. return hash;
  4405. };
  4406. /**
  4407. * Copy the quaternion to an array
  4408. * @returns a new array populated with 4 elements from the quaternion coordinates
  4409. */
  4410. Quaternion.prototype.asArray = function () {
  4411. return [this.x, this.y, this.z, this.w];
  4412. };
  4413. /**
  4414. * Check if two quaternions are equals
  4415. * @param otherQuaternion defines the second operand
  4416. * @return true if the current quaternion and the given one coordinates are strictly equals
  4417. */
  4418. Quaternion.prototype.equals = function (otherQuaternion) {
  4419. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4420. };
  4421. /**
  4422. * Clone the current quaternion
  4423. * @returns a new quaternion copied from the current one
  4424. */
  4425. Quaternion.prototype.clone = function () {
  4426. return new Quaternion(this.x, this.y, this.z, this.w);
  4427. };
  4428. /**
  4429. * Copy a quaternion to the current one
  4430. * @param other defines the other quaternion
  4431. * @returns the updated current quaternion
  4432. */
  4433. Quaternion.prototype.copyFrom = function (other) {
  4434. this.x = other.x;
  4435. this.y = other.y;
  4436. this.z = other.z;
  4437. this.w = other.w;
  4438. return this;
  4439. };
  4440. /**
  4441. * Updates the current quaternion with the given float coordinates
  4442. * @param x defines the x coordinate
  4443. * @param y defines the y coordinate
  4444. * @param z defines the z coordinate
  4445. * @param w defines the w coordinate
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4449. this.x = x;
  4450. this.y = y;
  4451. this.z = z;
  4452. this.w = w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion from the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.set = function (x, y, z, w) {
  4464. return this.copyFromFloats(x, y, z, w);
  4465. };
  4466. /**
  4467. * Adds two quaternions
  4468. * @param other defines the second operand
  4469. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4470. */
  4471. Quaternion.prototype.add = function (other) {
  4472. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4473. };
  4474. /**
  4475. * Add a quaternion to the current one
  4476. * @param other defines the quaternion to add
  4477. * @returns the current quaternion
  4478. */
  4479. Quaternion.prototype.addInPlace = function (other) {
  4480. this.x += other.x;
  4481. this.y += other.y;
  4482. this.z += other.z;
  4483. this.w += other.w;
  4484. return this;
  4485. };
  4486. /**
  4487. * Subtract two quaternions
  4488. * @param other defines the second operand
  4489. * @returns a new quaternion as the subtraction result of the given one from the current one
  4490. */
  4491. Quaternion.prototype.subtract = function (other) {
  4492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4493. };
  4494. /**
  4495. * Multiplies the current quaternion by a scale factor
  4496. * @param value defines the scale factor
  4497. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4498. */
  4499. Quaternion.prototype.scale = function (value) {
  4500. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4501. };
  4502. /**
  4503. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4504. * @param scale defines the scale factor
  4505. * @param result defines the Quaternion object where to store the result
  4506. * @returns the unmodified current quaternion
  4507. */
  4508. Quaternion.prototype.scaleToRef = function (scale, result) {
  4509. result.x = this.x * scale;
  4510. result.y = this.y * scale;
  4511. result.z = this.z * scale;
  4512. result.w = this.w * scale;
  4513. return this;
  4514. };
  4515. /**
  4516. * Multiplies in place the current quaternion by a scale factor
  4517. * @param value defines the scale factor
  4518. * @returns the current modified quaternion
  4519. */
  4520. Quaternion.prototype.scaleInPlace = function (value) {
  4521. this.x *= value;
  4522. this.y *= value;
  4523. this.z *= value;
  4524. this.w *= value;
  4525. return this;
  4526. };
  4527. /**
  4528. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4529. * @param scale defines the scale factor
  4530. * @param result defines the Quaternion object where to store the result
  4531. * @returns the unmodified current quaternion
  4532. */
  4533. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4534. result.x += this.x * scale;
  4535. result.y += this.y * scale;
  4536. result.z += this.z * scale;
  4537. result.w += this.w * scale;
  4538. return this;
  4539. };
  4540. /**
  4541. * Multiplies two quaternions
  4542. * @param q1 defines the second operand
  4543. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4544. */
  4545. Quaternion.prototype.multiply = function (q1) {
  4546. var result = new Quaternion(0, 0, 0, 1.0);
  4547. this.multiplyToRef(q1, result);
  4548. return result;
  4549. };
  4550. /**
  4551. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4552. * @param q1 defines the second operand
  4553. * @param result defines the target quaternion
  4554. * @returns the current quaternion
  4555. */
  4556. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4557. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4558. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4559. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4560. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4561. result.copyFromFloats(x, y, z, w);
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4566. * @param q1 defines the second operand
  4567. * @returns the currentupdated quaternion
  4568. */
  4569. Quaternion.prototype.multiplyInPlace = function (q1) {
  4570. this.multiplyToRef(q1, this);
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4575. * @param ref defines the target quaternion
  4576. * @returns the current quaternion
  4577. */
  4578. Quaternion.prototype.conjugateToRef = function (ref) {
  4579. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4580. return this;
  4581. };
  4582. /**
  4583. * Conjugates in place (1-q) the current quaternion
  4584. * @returns the current updated quaternion
  4585. */
  4586. Quaternion.prototype.conjugateInPlace = function () {
  4587. this.x *= -1;
  4588. this.y *= -1;
  4589. this.z *= -1;
  4590. return this;
  4591. };
  4592. /**
  4593. * Conjugates in place (1-q) the current quaternion
  4594. * @returns a new quaternion
  4595. */
  4596. Quaternion.prototype.conjugate = function () {
  4597. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4598. return result;
  4599. };
  4600. /**
  4601. * Gets length of current quaternion
  4602. * @returns the quaternion length (float)
  4603. */
  4604. Quaternion.prototype.length = function () {
  4605. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4606. };
  4607. /**
  4608. * Normalize in place the current quaternion
  4609. * @returns the current updated quaternion
  4610. */
  4611. Quaternion.prototype.normalize = function () {
  4612. var length = 1.0 / this.length();
  4613. this.x *= length;
  4614. this.y *= length;
  4615. this.z *= length;
  4616. this.w *= length;
  4617. return this;
  4618. };
  4619. /**
  4620. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns a new Vector3 containing the Euler angles
  4623. */
  4624. Quaternion.prototype.toEulerAngles = function (order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var result = Vector3.Zero();
  4627. this.toEulerAnglesToRef(result, order);
  4628. return result;
  4629. };
  4630. /**
  4631. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4632. * @param result defines the vector which will be filled with the Euler angles
  4633. * @param order is a reserved parameter and is ignore for now
  4634. * @returns the current unchanged quaternion
  4635. */
  4636. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4637. if (order === void 0) { order = "YZX"; }
  4638. var qz = this.z;
  4639. var qx = this.x;
  4640. var qy = this.y;
  4641. var qw = this.w;
  4642. var sqw = qw * qw;
  4643. var sqz = qz * qz;
  4644. var sqx = qx * qx;
  4645. var sqy = qy * qy;
  4646. var zAxisY = qy * qz - qx * qw;
  4647. var limit = .4999999;
  4648. if (zAxisY < -limit) {
  4649. result.y = 2 * Math.atan2(qy, qw);
  4650. result.x = Math.PI / 2;
  4651. result.z = 0;
  4652. }
  4653. else if (zAxisY > limit) {
  4654. result.y = 2 * Math.atan2(qy, qw);
  4655. result.x = -Math.PI / 2;
  4656. result.z = 0;
  4657. }
  4658. else {
  4659. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4660. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4661. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4662. }
  4663. return this;
  4664. };
  4665. /**
  4666. * Updates the given rotation matrix with the current quaternion values
  4667. * @param result defines the target matrix
  4668. * @returns the current unchanged quaternion
  4669. */
  4670. Quaternion.prototype.toRotationMatrix = function (result) {
  4671. var xx = this.x * this.x;
  4672. var yy = this.y * this.y;
  4673. var zz = this.z * this.z;
  4674. var xy = this.x * this.y;
  4675. var zw = this.z * this.w;
  4676. var zx = this.z * this.x;
  4677. var yw = this.y * this.w;
  4678. var yz = this.y * this.z;
  4679. var xw = this.x * this.w;
  4680. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4681. result.m[1] = 2.0 * (xy + zw);
  4682. result.m[2] = 2.0 * (zx - yw);
  4683. result.m[3] = 0;
  4684. result.m[4] = 2.0 * (xy - zw);
  4685. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4686. result.m[6] = 2.0 * (yz + xw);
  4687. result.m[7] = 0;
  4688. result.m[8] = 2.0 * (zx + yw);
  4689. result.m[9] = 2.0 * (yz - xw);
  4690. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4691. result.m[11] = 0;
  4692. result.m[12] = 0;
  4693. result.m[13] = 0;
  4694. result.m[14] = 0;
  4695. result.m[15] = 1.0;
  4696. result._markAsUpdated();
  4697. return this;
  4698. };
  4699. /**
  4700. * Updates the current quaternion from the given rotation matrix values
  4701. * @param matrix defines the source matrix
  4702. * @returns the current updated quaternion
  4703. */
  4704. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4705. Quaternion.FromRotationMatrixToRef(matrix, this);
  4706. return this;
  4707. };
  4708. // Statics
  4709. /**
  4710. * Creates a new quaternion from a rotation matrix
  4711. * @param matrix defines the source matrix
  4712. * @returns a new quaternion created from the given rotation matrix values
  4713. */
  4714. Quaternion.FromRotationMatrix = function (matrix) {
  4715. var result = new Quaternion();
  4716. Quaternion.FromRotationMatrixToRef(matrix, result);
  4717. return result;
  4718. };
  4719. /**
  4720. * Updates the given quaternion with the given rotation matrix values
  4721. * @param matrix defines the source matrix
  4722. * @param result defines the target quaternion
  4723. */
  4724. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4725. var data = matrix.m;
  4726. var m11 = data[0], m12 = data[4], m13 = data[8];
  4727. var m21 = data[1], m22 = data[5], m23 = data[9];
  4728. var m31 = data[2], m32 = data[6], m33 = data[10];
  4729. var trace = m11 + m22 + m33;
  4730. var s;
  4731. if (trace > 0) {
  4732. s = 0.5 / Math.sqrt(trace + 1.0);
  4733. result.w = 0.25 / s;
  4734. result.x = (m32 - m23) * s;
  4735. result.y = (m13 - m31) * s;
  4736. result.z = (m21 - m12) * s;
  4737. }
  4738. else if (m11 > m22 && m11 > m33) {
  4739. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4740. result.w = (m32 - m23) / s;
  4741. result.x = 0.25 * s;
  4742. result.y = (m12 + m21) / s;
  4743. result.z = (m13 + m31) / s;
  4744. }
  4745. else if (m22 > m33) {
  4746. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4747. result.w = (m13 - m31) / s;
  4748. result.x = (m12 + m21) / s;
  4749. result.y = 0.25 * s;
  4750. result.z = (m23 + m32) / s;
  4751. }
  4752. else {
  4753. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4754. result.w = (m21 - m12) / s;
  4755. result.x = (m13 + m31) / s;
  4756. result.y = (m23 + m32) / s;
  4757. result.z = 0.25 * s;
  4758. }
  4759. };
  4760. /**
  4761. * Returns the dot product (float) between the quaternions "left" and "right"
  4762. * @param left defines the left operand
  4763. * @param right defines the right operand
  4764. * @returns the dot product
  4765. */
  4766. Quaternion.Dot = function (left, right) {
  4767. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4768. };
  4769. /**
  4770. * Checks if the two quaternions are close to each other
  4771. * @param quat0 defines the first quaternion to check
  4772. * @param quat1 defines the second quaternion to check
  4773. * @returns true if the two quaternions are close to each other
  4774. */
  4775. Quaternion.AreClose = function (quat0, quat1) {
  4776. var dot = Quaternion.Dot(quat0, quat1);
  4777. return dot >= 0;
  4778. };
  4779. /**
  4780. * Creates an empty quaternion
  4781. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4782. */
  4783. Quaternion.Zero = function () {
  4784. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4785. };
  4786. /**
  4787. * Inverse a given quaternion
  4788. * @param q defines the source quaternion
  4789. * @returns a new quaternion as the inverted current quaternion
  4790. */
  4791. Quaternion.Inverse = function (q) {
  4792. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4793. };
  4794. /**
  4795. * Creates an identity quaternion
  4796. * @returns the identity quaternion
  4797. */
  4798. Quaternion.Identity = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4800. };
  4801. /**
  4802. * Gets a boolean indicating if the given quaternion is identity
  4803. * @param quaternion defines the quaternion to check
  4804. * @returns true if the quaternion is identity
  4805. */
  4806. Quaternion.IsIdentity = function (quaternion) {
  4807. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4808. };
  4809. /**
  4810. * Creates a quaternion from a rotation around an axis
  4811. * @param axis defines the axis to use
  4812. * @param angle defines the angle to use
  4813. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4814. */
  4815. Quaternion.RotationAxis = function (axis, angle) {
  4816. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4817. };
  4818. /**
  4819. * Creates a rotation around an axis and stores it into the given quaternion
  4820. * @param axis defines the axis to use
  4821. * @param angle defines the angle to use
  4822. * @param result defines the target quaternion
  4823. * @returns the target quaternion
  4824. */
  4825. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4826. var sin = Math.sin(angle / 2);
  4827. axis.normalize();
  4828. result.w = Math.cos(angle / 2);
  4829. result.x = axis.x * sin;
  4830. result.y = axis.y * sin;
  4831. result.z = axis.z * sin;
  4832. return result;
  4833. };
  4834. /**
  4835. * Creates a new quaternion from data stored into an array
  4836. * @param array defines the data source
  4837. * @param offset defines the offset in the source array where the data starts
  4838. * @returns a new quaternion
  4839. */
  4840. Quaternion.FromArray = function (array, offset) {
  4841. if (!offset) {
  4842. offset = 0;
  4843. }
  4844. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4845. };
  4846. /**
  4847. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @returns the new quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4854. var q = new Quaternion();
  4855. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4856. return q;
  4857. };
  4858. /**
  4859. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4860. * @param yaw defines the rotation around Y axis
  4861. * @param pitch defines the rotation around X axis
  4862. * @param roll defines the rotation around Z axis
  4863. * @param result defines the target quaternion
  4864. */
  4865. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4866. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4867. var halfRoll = roll * 0.5;
  4868. var halfPitch = pitch * 0.5;
  4869. var halfYaw = yaw * 0.5;
  4870. var sinRoll = Math.sin(halfRoll);
  4871. var cosRoll = Math.cos(halfRoll);
  4872. var sinPitch = Math.sin(halfPitch);
  4873. var cosPitch = Math.cos(halfPitch);
  4874. var sinYaw = Math.sin(halfYaw);
  4875. var cosYaw = Math.cos(halfYaw);
  4876. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4877. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4878. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4879. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @returns the new quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4889. var result = new Quaternion();
  4890. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4891. return result;
  4892. };
  4893. /**
  4894. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4895. * @param alpha defines the rotation around first axis
  4896. * @param beta defines the rotation around second axis
  4897. * @param gamma defines the rotation around third axis
  4898. * @param result defines the target quaternion
  4899. */
  4900. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4901. // Produces a quaternion from Euler angles in the z-x-z orientation
  4902. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4903. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4904. var halfBeta = beta * 0.5;
  4905. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4906. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4907. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4908. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4909. };
  4910. /**
  4911. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @returns the new quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4918. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4919. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4920. return quat;
  4921. };
  4922. /**
  4923. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4924. * @param axis1 defines the first axis
  4925. * @param axis2 defines the second axis
  4926. * @param axis3 defines the third axis
  4927. * @param ref defines the target quaternion
  4928. */
  4929. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4930. var rotMat = MathTmp.Matrix[0];
  4931. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4932. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @returns the new interpolated quaternion
  4940. */
  4941. Quaternion.Slerp = function (left, right, amount) {
  4942. var result = Quaternion.Identity();
  4943. Quaternion.SlerpToRef(left, right, amount, result);
  4944. return result;
  4945. };
  4946. /**
  4947. * Interpolates between two quaternions and stores it into a target quaternion
  4948. * @param left defines first quaternion
  4949. * @param right defines second quaternion
  4950. * @param amount defines the gradient to use
  4951. * @param result defines the target quaternion
  4952. */
  4953. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4954. var num2;
  4955. var num3;
  4956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4957. var flag = false;
  4958. if (num4 < 0) {
  4959. flag = true;
  4960. num4 = -num4;
  4961. }
  4962. if (num4 > 0.999999) {
  4963. num3 = 1 - amount;
  4964. num2 = flag ? -amount : amount;
  4965. }
  4966. else {
  4967. var num5 = Math.acos(num4);
  4968. var num6 = (1.0 / Math.sin(num5));
  4969. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4970. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4971. }
  4972. result.x = (num3 * left.x) + (num2 * right.x);
  4973. result.y = (num3 * left.y) + (num2 * right.y);
  4974. result.z = (num3 * left.z) + (num2 * right.z);
  4975. result.w = (num3 * left.w) + (num2 * right.w);
  4976. };
  4977. /**
  4978. * Interpolate between two quaternions using Hermite interpolation
  4979. * @param value1 defines first quaternion
  4980. * @param tangent1 defines the incoming tangent
  4981. * @param value2 defines second quaternion
  4982. * @param tangent2 defines the outgoing tangent
  4983. * @param amount defines the target quaternion
  4984. * @returns the new interpolated quaternion
  4985. */
  4986. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4987. var squared = amount * amount;
  4988. var cubed = amount * squared;
  4989. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4990. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4991. var part3 = (cubed - (2.0 * squared)) + amount;
  4992. var part4 = cubed - squared;
  4993. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4994. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4995. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4996. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4997. return new Quaternion(x, y, z, w);
  4998. };
  4999. return Quaternion;
  5000. }());
  5001. BABYLON.Quaternion = Quaternion;
  5002. /**
  5003. * Class used to store matrix data (4x4)
  5004. */
  5005. var Matrix = /** @class */ (function () {
  5006. /**
  5007. * Creates an empty matrix (filled with zeros)
  5008. */
  5009. function Matrix() {
  5010. this._isIdentity = false;
  5011. this._isIdentityDirty = true;
  5012. /**
  5013. * Gets or sets the internal data of the matrix
  5014. */
  5015. this.m = new Float32Array(16);
  5016. this._markAsUpdated();
  5017. }
  5018. /** @hidden */
  5019. Matrix.prototype._markAsUpdated = function () {
  5020. this.updateFlag = Matrix._updateFlagSeed++;
  5021. this._isIdentityDirty = true;
  5022. };
  5023. // Properties
  5024. /**
  5025. * Check if the current matrix is indentity
  5026. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5027. * @returns true is the matrix is the identity matrix
  5028. */
  5029. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5030. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5031. if (this._isIdentityDirty) {
  5032. this._isIdentityDirty = false;
  5033. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5037. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5038. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5039. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5040. this._isIdentity = false;
  5041. }
  5042. else {
  5043. this._isIdentity = true;
  5044. }
  5045. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5046. this._isIdentity = false;
  5047. }
  5048. }
  5049. return this._isIdentity;
  5050. };
  5051. /**
  5052. * Gets the determinant of the matrix
  5053. * @returns the matrix determinant
  5054. */
  5055. Matrix.prototype.determinant = function () {
  5056. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5057. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5058. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5059. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5060. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5061. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5062. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5063. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5064. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5065. };
  5066. // Methods
  5067. /**
  5068. * Returns the matrix as a Float32Array
  5069. * @returns the matrix underlying array
  5070. */
  5071. Matrix.prototype.toArray = function () {
  5072. return this.m;
  5073. };
  5074. /**
  5075. * Returns the matrix as a Float32Array
  5076. * @returns the matrix underlying array.
  5077. */
  5078. Matrix.prototype.asArray = function () {
  5079. return this.toArray();
  5080. };
  5081. /**
  5082. * Inverts the current matrix in place
  5083. * @returns the current inverted matrix
  5084. */
  5085. Matrix.prototype.invert = function () {
  5086. this.invertToRef(this);
  5087. return this;
  5088. };
  5089. /**
  5090. * Sets all the matrix elements to zero
  5091. * @returns the current matrix
  5092. */
  5093. Matrix.prototype.reset = function () {
  5094. for (var index = 0; index < 16; index++) {
  5095. this.m[index] = 0.0;
  5096. }
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Adds the current matrix with a second one
  5102. * @param other defines the matrix to add
  5103. * @returns a new matrix as the addition of the current matrix and the given one
  5104. */
  5105. Matrix.prototype.add = function (other) {
  5106. var result = new Matrix();
  5107. this.addToRef(other, result);
  5108. return result;
  5109. };
  5110. /**
  5111. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5112. * @param other defines the matrix to add
  5113. * @param result defines the target matrix
  5114. * @returns the current matrix
  5115. */
  5116. Matrix.prototype.addToRef = function (other, result) {
  5117. for (var index = 0; index < 16; index++) {
  5118. result.m[index] = this.m[index] + other.m[index];
  5119. }
  5120. result._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Adds in place the given matrix to the current matrix
  5125. * @param other defines the second operand
  5126. * @returns the current updated matrix
  5127. */
  5128. Matrix.prototype.addToSelf = function (other) {
  5129. for (var index = 0; index < 16; index++) {
  5130. this.m[index] += other.m[index];
  5131. }
  5132. this._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the given matrix to the current inverted Matrix
  5137. * @param other defines the target matrix
  5138. * @returns the unmodified current matrix
  5139. */
  5140. Matrix.prototype.invertToRef = function (other) {
  5141. var l1 = this.m[0];
  5142. var l2 = this.m[1];
  5143. var l3 = this.m[2];
  5144. var l4 = this.m[3];
  5145. var l5 = this.m[4];
  5146. var l6 = this.m[5];
  5147. var l7 = this.m[6];
  5148. var l8 = this.m[7];
  5149. var l9 = this.m[8];
  5150. var l10 = this.m[9];
  5151. var l11 = this.m[10];
  5152. var l12 = this.m[11];
  5153. var l13 = this.m[12];
  5154. var l14 = this.m[13];
  5155. var l15 = this.m[14];
  5156. var l16 = this.m[15];
  5157. var l17 = (l11 * l16) - (l12 * l15);
  5158. var l18 = (l10 * l16) - (l12 * l14);
  5159. var l19 = (l10 * l15) - (l11 * l14);
  5160. var l20 = (l9 * l16) - (l12 * l13);
  5161. var l21 = (l9 * l15) - (l11 * l13);
  5162. var l22 = (l9 * l14) - (l10 * l13);
  5163. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5164. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5165. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5166. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5167. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5168. var l28 = (l7 * l16) - (l8 * l15);
  5169. var l29 = (l6 * l16) - (l8 * l14);
  5170. var l30 = (l6 * l15) - (l7 * l14);
  5171. var l31 = (l5 * l16) - (l8 * l13);
  5172. var l32 = (l5 * l15) - (l7 * l13);
  5173. var l33 = (l5 * l14) - (l6 * l13);
  5174. var l34 = (l7 * l12) - (l8 * l11);
  5175. var l35 = (l6 * l12) - (l8 * l10);
  5176. var l36 = (l6 * l11) - (l7 * l10);
  5177. var l37 = (l5 * l12) - (l8 * l9);
  5178. var l38 = (l5 * l11) - (l7 * l9);
  5179. var l39 = (l5 * l10) - (l6 * l9);
  5180. other.m[0] = l23 * l27;
  5181. other.m[4] = l24 * l27;
  5182. other.m[8] = l25 * l27;
  5183. other.m[12] = l26 * l27;
  5184. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5185. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5186. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5187. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5188. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5189. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5190. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5191. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5192. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5193. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5194. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5195. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5196. other._markAsUpdated();
  5197. return this;
  5198. };
  5199. /**
  5200. * Inserts the translation vector (using 3 floats) in the current matrix
  5201. * @param x defines the 1st component of the translation
  5202. * @param y defines the 2nd component of the translation
  5203. * @param z defines the 3rd component of the translation
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5207. this.m[12] = x;
  5208. this.m[13] = y;
  5209. this.m[14] = z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Inserts the translation vector in the current matrix
  5215. * @param vector3 defines the translation to insert
  5216. * @returns the current updated matrix
  5217. */
  5218. Matrix.prototype.setTranslation = function (vector3) {
  5219. this.m[12] = vector3.x;
  5220. this.m[13] = vector3.y;
  5221. this.m[14] = vector3.z;
  5222. this._markAsUpdated();
  5223. return this;
  5224. };
  5225. /**
  5226. * Gets the translation value of the current matrix
  5227. * @returns a new Vector3 as the extracted translation from the matrix
  5228. */
  5229. Matrix.prototype.getTranslation = function () {
  5230. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5231. };
  5232. /**
  5233. * Fill a Vector3 with the extracted translation from the matrix
  5234. * @param result defines the Vector3 where to store the translation
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.getTranslationToRef = function (result) {
  5238. result.x = this.m[12];
  5239. result.y = this.m[13];
  5240. result.z = this.m[14];
  5241. return this;
  5242. };
  5243. /**
  5244. * Remove rotation and scaling part from the matrix
  5245. * @returns the updated matrix
  5246. */
  5247. Matrix.prototype.removeRotationAndScaling = function () {
  5248. this.setRowFromFloats(0, 1, 0, 0, 0);
  5249. this.setRowFromFloats(1, 0, 1, 0, 0);
  5250. this.setRowFromFloats(2, 0, 0, 1, 0);
  5251. return this;
  5252. };
  5253. /**
  5254. * Multiply two matrices
  5255. * @param other defines the second operand
  5256. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5257. */
  5258. Matrix.prototype.multiply = function (other) {
  5259. var result = new Matrix();
  5260. this.multiplyToRef(other, result);
  5261. return result;
  5262. };
  5263. /**
  5264. * Copy the current matrix from the given one
  5265. * @param other defines the source matrix
  5266. * @returns the current updated matrix
  5267. */
  5268. Matrix.prototype.copyFrom = function (other) {
  5269. for (var index = 0; index < 16; index++) {
  5270. this.m[index] = other.m[index];
  5271. }
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Populates the given array from the starting index with the current matrix values
  5277. * @param array defines the target array
  5278. * @param offset defines the offset in the target array where to start storing values
  5279. * @returns the current matrix
  5280. */
  5281. Matrix.prototype.copyToArray = function (array, offset) {
  5282. if (offset === void 0) { offset = 0; }
  5283. for (var index = 0; index < 16; index++) {
  5284. array[offset + index] = this.m[index];
  5285. }
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the matrix where to store the multiplication
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToRef = function (other, result) {
  5295. this.multiplyToArray(other, result.m, 0);
  5296. result._markAsUpdated();
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the array where to store the multiplication
  5303. * @param offset defines the offset in the target array where to start storing values
  5304. * @returns the current matrix
  5305. */
  5306. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5307. var tm0 = this.m[0];
  5308. var tm1 = this.m[1];
  5309. var tm2 = this.m[2];
  5310. var tm3 = this.m[3];
  5311. var tm4 = this.m[4];
  5312. var tm5 = this.m[5];
  5313. var tm6 = this.m[6];
  5314. var tm7 = this.m[7];
  5315. var tm8 = this.m[8];
  5316. var tm9 = this.m[9];
  5317. var tm10 = this.m[10];
  5318. var tm11 = this.m[11];
  5319. var tm12 = this.m[12];
  5320. var tm13 = this.m[13];
  5321. var tm14 = this.m[14];
  5322. var tm15 = this.m[15];
  5323. var om0 = other.m[0];
  5324. var om1 = other.m[1];
  5325. var om2 = other.m[2];
  5326. var om3 = other.m[3];
  5327. var om4 = other.m[4];
  5328. var om5 = other.m[5];
  5329. var om6 = other.m[6];
  5330. var om7 = other.m[7];
  5331. var om8 = other.m[8];
  5332. var om9 = other.m[9];
  5333. var om10 = other.m[10];
  5334. var om11 = other.m[11];
  5335. var om12 = other.m[12];
  5336. var om13 = other.m[13];
  5337. var om14 = other.m[14];
  5338. var om15 = other.m[15];
  5339. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5340. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5341. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5342. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5343. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5344. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5345. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5346. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5347. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5348. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5349. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5350. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5351. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5352. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5353. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5354. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5355. return this;
  5356. };
  5357. /**
  5358. * Check equality between this matrix and a second one
  5359. * @param value defines the second matrix to compare
  5360. * @returns true is the current matrix and the given one values are strictly equal
  5361. */
  5362. Matrix.prototype.equals = function (value) {
  5363. return value &&
  5364. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5365. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5366. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5367. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5368. };
  5369. /**
  5370. * Clone the current matrix
  5371. * @returns a new matrix from the current matrix
  5372. */
  5373. Matrix.prototype.clone = function () {
  5374. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5375. };
  5376. /**
  5377. * Returns the name of the current matrix class
  5378. * @returns the string "Matrix"
  5379. */
  5380. Matrix.prototype.getClassName = function () {
  5381. return "Matrix";
  5382. };
  5383. /**
  5384. * Gets the hash code of the current matrix
  5385. * @returns the hash code
  5386. */
  5387. Matrix.prototype.getHashCode = function () {
  5388. var hash = this.m[0] || 0;
  5389. for (var i = 1; i < 16; i++) {
  5390. hash = (hash * 397) ^ (this.m[i] || 0);
  5391. }
  5392. return hash;
  5393. };
  5394. /**
  5395. * Decomposes the current Matrix into a translation, rotation and scaling components
  5396. * @param scale defines the scale vector3 given as a reference to update
  5397. * @param rotation defines the rotation quaternion given as a reference to update
  5398. * @param translation defines the translation vector3 given as a reference to update
  5399. * @returns true if operation was successful
  5400. */
  5401. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5402. if (translation) {
  5403. translation.x = this.m[12];
  5404. translation.y = this.m[13];
  5405. translation.z = this.m[14];
  5406. }
  5407. scale = scale || MathTmp.Vector3[0];
  5408. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5409. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5410. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5411. if (this.determinant() <= 0) {
  5412. scale.y *= -1;
  5413. }
  5414. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5415. if (rotation) {
  5416. rotation.x = 0;
  5417. rotation.y = 0;
  5418. rotation.z = 0;
  5419. rotation.w = 1;
  5420. }
  5421. return false;
  5422. }
  5423. if (rotation) {
  5424. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5425. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5426. }
  5427. return true;
  5428. };
  5429. /**
  5430. * Gets specific row of the matrix
  5431. * @param index defines the number of the row to get
  5432. * @returns the index-th row of the current matrix as a new Vector4
  5433. */
  5434. Matrix.prototype.getRow = function (index) {
  5435. if (index < 0 || index > 3) {
  5436. return null;
  5437. }
  5438. var i = index * 4;
  5439. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5440. };
  5441. /**
  5442. * Sets the index-th row of the current matrix to the vector4 values
  5443. * @param index defines the number of the row to set
  5444. * @param row defines the target vector4
  5445. * @returns the updated current matrix
  5446. */
  5447. Matrix.prototype.setRow = function (index, row) {
  5448. if (index < 0 || index > 3) {
  5449. return this;
  5450. }
  5451. var i = index * 4;
  5452. this.m[i + 0] = row.x;
  5453. this.m[i + 1] = row.y;
  5454. this.m[i + 2] = row.z;
  5455. this.m[i + 3] = row.w;
  5456. this._markAsUpdated();
  5457. return this;
  5458. };
  5459. /**
  5460. * Compute the transpose of the matrix
  5461. * @returns the new transposed matrix
  5462. */
  5463. Matrix.prototype.transpose = function () {
  5464. return Matrix.Transpose(this);
  5465. };
  5466. /**
  5467. * Compute the transpose of the matrix and store it in a given matrix
  5468. * @param result defines the target matrix
  5469. * @returns the current matrix
  5470. */
  5471. Matrix.prototype.transposeToRef = function (result) {
  5472. Matrix.TransposeToRef(this, result);
  5473. return this;
  5474. };
  5475. /**
  5476. * Sets the index-th row of the current matrix with the given 4 x float values
  5477. * @param index defines the row index
  5478. * @param x defines the x component to set
  5479. * @param y defines the y component to set
  5480. * @param z defines the z component to set
  5481. * @param w defines the w component to set
  5482. * @returns the updated current matrix
  5483. */
  5484. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5485. if (index < 0 || index > 3) {
  5486. return this;
  5487. }
  5488. var i = index * 4;
  5489. this.m[i + 0] = x;
  5490. this.m[i + 1] = y;
  5491. this.m[i + 2] = z;
  5492. this.m[i + 3] = w;
  5493. this._markAsUpdated();
  5494. return this;
  5495. };
  5496. /**
  5497. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5498. * @param scale defines the scale factor
  5499. * @returns a new matrix
  5500. */
  5501. Matrix.prototype.scale = function (scale) {
  5502. var result = new Matrix();
  5503. this.scaleToRef(scale, result);
  5504. return result;
  5505. };
  5506. /**
  5507. * Scale the current matrix values by a factor to a given result matrix
  5508. * @param scale defines the scale factor
  5509. * @param result defines the matrix to store the result
  5510. * @returns the current matrix
  5511. */
  5512. Matrix.prototype.scaleToRef = function (scale, result) {
  5513. for (var index = 0; index < 16; index++) {
  5514. result.m[index] = this.m[index] * scale;
  5515. }
  5516. result._markAsUpdated();
  5517. return this;
  5518. };
  5519. /**
  5520. * Scale the current matrix values by a factor and add the result to a given matrix
  5521. * @param scale defines the scale factor
  5522. * @param result defines the Matrix to store the result
  5523. * @returns the current matrix
  5524. */
  5525. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5526. for (var index = 0; index < 16; index++) {
  5527. result.m[index] += this.m[index] * scale;
  5528. }
  5529. result._markAsUpdated();
  5530. return this;
  5531. };
  5532. /**
  5533. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5534. * @param ref matrix to store the result
  5535. */
  5536. Matrix.prototype.toNormalMatrix = function (ref) {
  5537. this.invertToRef(ref);
  5538. ref.transpose();
  5539. var m = ref.m;
  5540. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5541. };
  5542. /**
  5543. * Gets only rotation part of the current matrix
  5544. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5545. */
  5546. Matrix.prototype.getRotationMatrix = function () {
  5547. var result = Matrix.Identity();
  5548. this.getRotationMatrixToRef(result);
  5549. return result;
  5550. };
  5551. /**
  5552. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5553. * @param result defines the target matrix to store data to
  5554. * @returns the current matrix
  5555. */
  5556. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5557. var m = this.m;
  5558. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5559. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5560. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5561. if (this.determinant() <= 0) {
  5562. sy *= -1;
  5563. }
  5564. if (sx === 0 || sy === 0 || sz === 0) {
  5565. Matrix.IdentityToRef(result);
  5566. }
  5567. else {
  5568. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5569. }
  5570. return this;
  5571. };
  5572. // Statics
  5573. /**
  5574. * Creates a matrix from an array
  5575. * @param array defines the source array
  5576. * @param offset defines an offset in the source array
  5577. * @returns a new Matrix set from the starting index of the given array
  5578. */
  5579. Matrix.FromArray = function (array, offset) {
  5580. var result = new Matrix();
  5581. if (!offset) {
  5582. offset = 0;
  5583. }
  5584. Matrix.FromArrayToRef(array, offset, result);
  5585. return result;
  5586. };
  5587. /**
  5588. * Copy the content of an array into a given matrix
  5589. * @param array defines the source array
  5590. * @param offset defines an offset in the source array
  5591. * @param result defines the target matrix
  5592. */
  5593. Matrix.FromArrayToRef = function (array, offset, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] = array[index + offset];
  5596. }
  5597. result._markAsUpdated();
  5598. };
  5599. /**
  5600. * Stores an array into a matrix after having multiplied each component by a given factor
  5601. * @param array defines the source array
  5602. * @param offset defines the offset in the source array
  5603. * @param scale defines the scaling factor
  5604. * @param result defines the target matrix
  5605. */
  5606. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5607. for (var index = 0; index < 16; index++) {
  5608. result.m[index] = array[index + offset] * scale;
  5609. }
  5610. result._markAsUpdated();
  5611. };
  5612. /**
  5613. * Stores a list of values (16) inside a given matrix
  5614. * @param initialM11 defines 1st value of 1st row
  5615. * @param initialM12 defines 2nd value of 1st row
  5616. * @param initialM13 defines 3rd value of 1st row
  5617. * @param initialM14 defines 4th value of 1st row
  5618. * @param initialM21 defines 1st value of 2nd row
  5619. * @param initialM22 defines 2nd value of 2nd row
  5620. * @param initialM23 defines 3rd value of 2nd row
  5621. * @param initialM24 defines 4th value of 2nd row
  5622. * @param initialM31 defines 1st value of 3rd row
  5623. * @param initialM32 defines 2nd value of 3rd row
  5624. * @param initialM33 defines 3rd value of 3rd row
  5625. * @param initialM34 defines 4th value of 3rd row
  5626. * @param initialM41 defines 1st value of 4th row
  5627. * @param initialM42 defines 2nd value of 4th row
  5628. * @param initialM43 defines 3rd value of 4th row
  5629. * @param initialM44 defines 4th value of 4th row
  5630. * @param result defines the target matrix
  5631. */
  5632. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5633. result.m[0] = initialM11;
  5634. result.m[1] = initialM12;
  5635. result.m[2] = initialM13;
  5636. result.m[3] = initialM14;
  5637. result.m[4] = initialM21;
  5638. result.m[5] = initialM22;
  5639. result.m[6] = initialM23;
  5640. result.m[7] = initialM24;
  5641. result.m[8] = initialM31;
  5642. result.m[9] = initialM32;
  5643. result.m[10] = initialM33;
  5644. result.m[11] = initialM34;
  5645. result.m[12] = initialM41;
  5646. result.m[13] = initialM42;
  5647. result.m[14] = initialM43;
  5648. result.m[15] = initialM44;
  5649. result._markAsUpdated();
  5650. };
  5651. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5652. /**
  5653. * Gets an identity matrix that must not be updated
  5654. */
  5655. get: function () {
  5656. return Matrix._identityReadOnly;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. /**
  5662. * Creates new matrix from a list of values (16)
  5663. * @param initialM11 defines 1st value of 1st row
  5664. * @param initialM12 defines 2nd value of 1st row
  5665. * @param initialM13 defines 3rd value of 1st row
  5666. * @param initialM14 defines 4th value of 1st row
  5667. * @param initialM21 defines 1st value of 2nd row
  5668. * @param initialM22 defines 2nd value of 2nd row
  5669. * @param initialM23 defines 3rd value of 2nd row
  5670. * @param initialM24 defines 4th value of 2nd row
  5671. * @param initialM31 defines 1st value of 3rd row
  5672. * @param initialM32 defines 2nd value of 3rd row
  5673. * @param initialM33 defines 3rd value of 3rd row
  5674. * @param initialM34 defines 4th value of 3rd row
  5675. * @param initialM41 defines 1st value of 4th row
  5676. * @param initialM42 defines 2nd value of 4th row
  5677. * @param initialM43 defines 3rd value of 4th row
  5678. * @param initialM44 defines 4th value of 4th row
  5679. * @returns the new matrix
  5680. */
  5681. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5682. var result = new Matrix();
  5683. result.m[0] = initialM11;
  5684. result.m[1] = initialM12;
  5685. result.m[2] = initialM13;
  5686. result.m[3] = initialM14;
  5687. result.m[4] = initialM21;
  5688. result.m[5] = initialM22;
  5689. result.m[6] = initialM23;
  5690. result.m[7] = initialM24;
  5691. result.m[8] = initialM31;
  5692. result.m[9] = initialM32;
  5693. result.m[10] = initialM33;
  5694. result.m[11] = initialM34;
  5695. result.m[12] = initialM41;
  5696. result.m[13] = initialM42;
  5697. result.m[14] = initialM43;
  5698. result.m[15] = initialM44;
  5699. return result;
  5700. };
  5701. /**
  5702. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @returns a new matrix
  5707. */
  5708. Matrix.Compose = function (scale, rotation, translation) {
  5709. var result = Matrix.Identity();
  5710. Matrix.ComposeToRef(scale, rotation, translation, result);
  5711. return result;
  5712. };
  5713. /**
  5714. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5715. * @param scale defines the scale vector3
  5716. * @param rotation defines the rotation quaternion
  5717. * @param translation defines the translation vector3
  5718. * @param result defines the target matrix
  5719. */
  5720. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5721. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5722. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5723. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5724. result.setTranslation(translation);
  5725. };
  5726. /**
  5727. * Creates a new identity matrix
  5728. * @returns a new identity matrix
  5729. */
  5730. Matrix.Identity = function () {
  5731. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5732. };
  5733. /**
  5734. * Creates a new identity matrix and stores the result in a given matrix
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.IdentityToRef = function (result) {
  5738. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5739. };
  5740. /**
  5741. * Creates a new zero matrix
  5742. * @returns a new zero matrix
  5743. */
  5744. Matrix.Zero = function () {
  5745. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5746. };
  5747. /**
  5748. * Creates a new rotation matrix for "angle" radians around the X axis
  5749. * @param angle defines the angle (in radians) to use
  5750. * @return the new matrix
  5751. */
  5752. Matrix.RotationX = function (angle) {
  5753. var result = new Matrix();
  5754. Matrix.RotationXToRef(angle, result);
  5755. return result;
  5756. };
  5757. /**
  5758. * Creates a new matrix as the invert of a given matrix
  5759. * @param source defines the source matrix
  5760. * @returns the new matrix
  5761. */
  5762. Matrix.Invert = function (source) {
  5763. var result = new Matrix();
  5764. source.invertToRef(result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5769. * @param angle defines the angle (in radians) to use
  5770. * @param result defines the target matrix
  5771. */
  5772. Matrix.RotationXToRef = function (angle, result) {
  5773. var s = Math.sin(angle);
  5774. var c = Math.cos(angle);
  5775. result.m[0] = 1.0;
  5776. result.m[15] = 1.0;
  5777. result.m[5] = c;
  5778. result.m[10] = c;
  5779. result.m[9] = -s;
  5780. result.m[6] = s;
  5781. result.m[1] = 0.0;
  5782. result.m[2] = 0.0;
  5783. result.m[3] = 0.0;
  5784. result.m[4] = 0.0;
  5785. result.m[7] = 0.0;
  5786. result.m[8] = 0.0;
  5787. result.m[11] = 0.0;
  5788. result.m[12] = 0.0;
  5789. result.m[13] = 0.0;
  5790. result.m[14] = 0.0;
  5791. result._markAsUpdated();
  5792. };
  5793. /**
  5794. * Creates a new rotation matrix for "angle" radians around the Y axis
  5795. * @param angle defines the angle (in radians) to use
  5796. * @return the new matrix
  5797. */
  5798. Matrix.RotationY = function (angle) {
  5799. var result = new Matrix();
  5800. Matrix.RotationYToRef(angle, result);
  5801. return result;
  5802. };
  5803. /**
  5804. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5805. * @param angle defines the angle (in radians) to use
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.RotationYToRef = function (angle, result) {
  5809. var s = Math.sin(angle);
  5810. var c = Math.cos(angle);
  5811. result.m[5] = 1.0;
  5812. result.m[15] = 1.0;
  5813. result.m[0] = c;
  5814. result.m[2] = -s;
  5815. result.m[8] = s;
  5816. result.m[10] = c;
  5817. result.m[1] = 0.0;
  5818. result.m[3] = 0.0;
  5819. result.m[4] = 0.0;
  5820. result.m[6] = 0.0;
  5821. result.m[7] = 0.0;
  5822. result.m[9] = 0.0;
  5823. result.m[11] = 0.0;
  5824. result.m[12] = 0.0;
  5825. result.m[13] = 0.0;
  5826. result.m[14] = 0.0;
  5827. result._markAsUpdated();
  5828. };
  5829. /**
  5830. * Creates a new rotation matrix for "angle" radians around the Z axis
  5831. * @param angle defines the angle (in radians) to use
  5832. * @return the new matrix
  5833. */
  5834. Matrix.RotationZ = function (angle) {
  5835. var result = new Matrix();
  5836. Matrix.RotationZToRef(angle, result);
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationZToRef = function (angle, result) {
  5845. var s = Math.sin(angle);
  5846. var c = Math.cos(angle);
  5847. result.m[10] = 1.0;
  5848. result.m[15] = 1.0;
  5849. result.m[0] = c;
  5850. result.m[1] = s;
  5851. result.m[4] = -s;
  5852. result.m[5] = c;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[6] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[9] = 0.0;
  5859. result.m[11] = 0.0;
  5860. result.m[12] = 0.0;
  5861. result.m[13] = 0.0;
  5862. result.m[14] = 0.0;
  5863. result._markAsUpdated();
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @return the new matrix
  5870. */
  5871. Matrix.RotationAxis = function (axis, angle) {
  5872. var result = Matrix.Zero();
  5873. Matrix.RotationAxisToRef(axis, angle, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @param result defines the target matrix
  5881. */
  5882. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5883. var s = Math.sin(-angle);
  5884. var c = Math.cos(-angle);
  5885. var c1 = 1 - c;
  5886. axis.normalize();
  5887. result.m[0] = (axis.x * axis.x) * c1 + c;
  5888. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5889. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5890. result.m[3] = 0.0;
  5891. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5892. result.m[5] = (axis.y * axis.y) * c1 + c;
  5893. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5894. result.m[7] = 0.0;
  5895. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5896. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5897. result.m[10] = (axis.z * axis.z) * c1 + c;
  5898. result.m[11] = 0.0;
  5899. result.m[15] = 1.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a rotation matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @returns the new rotation matrix
  5908. */
  5909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5910. var result = new Matrix();
  5911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Creates a rotation matrix and stores it in a given matrix
  5916. * @param yaw defines the yaw angle in radians (Y axis)
  5917. * @param pitch defines the pitch angle in radians (X axis)
  5918. * @param roll defines the roll angle in radians (X axis)
  5919. * @param result defines the target matrix
  5920. */
  5921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5923. this._tempQuaternion.toRotationMatrix(result);
  5924. };
  5925. /**
  5926. * Creates a scaling matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Scaling = function (x, y, z) {
  5933. var result = Matrix.Zero();
  5934. Matrix.ScalingToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a scaling matrix and stores it in a given matrix
  5939. * @param x defines the scale factor on X axis
  5940. * @param y defines the scale factor on Y axis
  5941. * @param z defines the scale factor on Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.ScalingToRef = function (x, y, z, result) {
  5945. result.m[0] = x;
  5946. result.m[1] = 0.0;
  5947. result.m[2] = 0.0;
  5948. result.m[3] = 0.0;
  5949. result.m[4] = 0.0;
  5950. result.m[5] = y;
  5951. result.m[6] = 0.0;
  5952. result.m[7] = 0.0;
  5953. result.m[8] = 0.0;
  5954. result.m[9] = 0.0;
  5955. result.m[10] = z;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result.m[15] = 1.0;
  5961. result._markAsUpdated();
  5962. };
  5963. /**
  5964. * Creates a translation matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @returns the new matrix
  5969. */
  5970. Matrix.Translation = function (x, y, z) {
  5971. var result = Matrix.Identity();
  5972. Matrix.TranslationToRef(x, y, z, result);
  5973. return result;
  5974. };
  5975. /**
  5976. * Creates a translation matrix and stores it in a given matrix
  5977. * @param x defines the translation on X axis
  5978. * @param y defines the translation on Y axis
  5979. * @param z defines the translationon Z axis
  5980. * @param result defines the target matrix
  5981. */
  5982. Matrix.TranslationToRef = function (x, y, z, result) {
  5983. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5984. };
  5985. /**
  5986. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @returns the new matrix
  5991. */
  5992. Matrix.Lerp = function (startValue, endValue, gradient) {
  5993. var result = Matrix.Zero();
  5994. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5999. * @param startValue defines the start value
  6000. * @param endValue defines the end value
  6001. * @param gradient defines the gradient factor
  6002. * @param result defines the Matrix object where to store data
  6003. */
  6004. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6005. for (var index = 0; index < 16; index++) {
  6006. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6007. }
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Builds a new matrix whose values are computed by:
  6012. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6013. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6014. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6015. * @param startValue defines the first matrix
  6016. * @param endValue defines the second matrix
  6017. * @param gradient defines the gradient between the two matrices
  6018. * @returns the new matrix
  6019. */
  6020. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6021. var result = Matrix.Zero();
  6022. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6023. return result;
  6024. };
  6025. /**
  6026. * Update a matrix to values which are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6036. var startScale = MathTmp.Vector3[0];
  6037. var startRotation = MathTmp.Quaternion[0];
  6038. var startTranslation = MathTmp.Vector3[1];
  6039. startValue.decompose(startScale, startRotation, startTranslation);
  6040. var endScale = MathTmp.Vector3[2];
  6041. var endRotation = MathTmp.Quaternion[1];
  6042. var endTranslation = MathTmp.Vector3[3];
  6043. endValue.decompose(endScale, endRotation, endTranslation);
  6044. var resultScale = MathTmp.Vector3[4];
  6045. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6046. var resultRotation = MathTmp.Quaternion[2];
  6047. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6048. var resultTranslation = MathTmp.Vector3[5];
  6049. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6050. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6051. };
  6052. /**
  6053. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6054. * This function works in left handed mode
  6055. * @param eye defines the final position of the entity
  6056. * @param target defines where the entity should look at
  6057. * @param up defines the up vector for the entity
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.LookAtLH = function (eye, target, up) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LookAtLHToRef(eye, target, up, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6067. * This function works in left handed mode
  6068. * @param eye defines the final position of the entity
  6069. * @param target defines where the entity should look at
  6070. * @param up defines the up vector for the entity
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6074. // Z axis
  6075. target.subtractToRef(eye, this._zAxis);
  6076. this._zAxis.normalize();
  6077. // X axis
  6078. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6079. if (this._xAxis.lengthSquared() === 0) {
  6080. this._xAxis.x = 1.0;
  6081. }
  6082. else {
  6083. this._xAxis.normalize();
  6084. }
  6085. // Y axis
  6086. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6087. this._yAxis.normalize();
  6088. // Eye angles
  6089. var ex = -Vector3.Dot(this._xAxis, eye);
  6090. var ey = -Vector3.Dot(this._yAxis, eye);
  6091. var ez = -Vector3.Dot(this._zAxis, eye);
  6092. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6093. };
  6094. /**
  6095. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6096. * This function works in right handed mode
  6097. * @param eye defines the final position of the entity
  6098. * @param target defines where the entity should look at
  6099. * @param up defines the up vector for the entity
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.LookAtRH = function (eye, target, up) {
  6103. var result = Matrix.Zero();
  6104. Matrix.LookAtRHToRef(eye, target, up, result);
  6105. return result;
  6106. };
  6107. /**
  6108. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6109. * This function works in right handed mode
  6110. * @param eye defines the final position of the entity
  6111. * @param target defines where the entity should look at
  6112. * @param up defines the up vector for the entity
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6116. // Z axis
  6117. eye.subtractToRef(target, this._zAxis);
  6118. this._zAxis.normalize();
  6119. // X axis
  6120. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6121. if (this._xAxis.lengthSquared() === 0) {
  6122. this._xAxis.x = 1.0;
  6123. }
  6124. else {
  6125. this._xAxis.normalize();
  6126. }
  6127. // Y axis
  6128. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6129. this._yAxis.normalize();
  6130. // Eye angles
  6131. var ex = -Vector3.Dot(this._xAxis, eye);
  6132. var ey = -Vector3.Dot(this._yAxis, eye);
  6133. var ez = -Vector3.Dot(this._zAxis, eye);
  6134. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6135. };
  6136. /**
  6137. * Create a left-handed orthographic projection matrix
  6138. * @param width defines the viewport width
  6139. * @param height defines the viewport height
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a left-handed orthographic projection matrix
  6143. */
  6144. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Store a left-handed orthographic projection to a given matrix
  6151. * @param width defines the viewport width
  6152. * @param height defines the viewport height
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. */
  6157. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6158. var n = znear;
  6159. var f = zfar;
  6160. var a = 2.0 / width;
  6161. var b = 2.0 / height;
  6162. var c = 2.0 / (f - n);
  6163. var d = -(f + n) / (f - n);
  6164. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6165. };
  6166. /**
  6167. * Create a left-handed orthographic projection matrix
  6168. * @param left defines the viewport left coordinate
  6169. * @param right defines the viewport right coordinate
  6170. * @param bottom defines the viewport bottom coordinate
  6171. * @param top defines the viewport top coordinate
  6172. * @param znear defines the near clip plane
  6173. * @param zfar defines the far clip plane
  6174. * @returns a new matrix as a left-handed orthographic projection matrix
  6175. */
  6176. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6177. var matrix = Matrix.Zero();
  6178. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6179. return matrix;
  6180. };
  6181. /**
  6182. * Stores a left-handed orthographic projection into a given matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @param result defines the target matrix
  6190. */
  6191. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6192. var n = znear;
  6193. var f = zfar;
  6194. var a = 2.0 / (right - left);
  6195. var b = 2.0 / (top - bottom);
  6196. var c = 2.0 / (f - n);
  6197. var d = -(f + n) / (f - n);
  6198. var i0 = (left + right) / (left - right);
  6199. var i1 = (top + bottom) / (bottom - top);
  6200. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6201. };
  6202. /**
  6203. * Creates a right-handed orthographic projection matrix
  6204. * @param left defines the viewport left coordinate
  6205. * @param right defines the viewport right coordinate
  6206. * @param bottom defines the viewport bottom coordinate
  6207. * @param top defines the viewport top coordinate
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a right-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Stores a right-handed orthographic projection into a given matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @param result defines the target matrix
  6226. */
  6227. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6228. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6229. result.m[10] *= -1.0;
  6230. };
  6231. /**
  6232. * Creates a left-handed perspective projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed perspective projection matrix
  6238. */
  6239. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. var n = znear;
  6242. var f = zfar;
  6243. var a = 2.0 * n / width;
  6244. var b = 2.0 * n / height;
  6245. var c = (f + n) / (f - n);
  6246. var d = -2.0 * f * n / (f - n);
  6247. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6248. return matrix;
  6249. };
  6250. /**
  6251. * Creates a left-handed perspective projection matrix
  6252. * @param fov defines the horizontal field of view
  6253. * @param aspect defines the aspect ratio
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a left-handed perspective projection matrix
  6257. */
  6258. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a left-handed perspective projection into a given matrix
  6265. * @param fov defines the horizontal field of view
  6266. * @param aspect defines the aspect ratio
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @param result defines the target matrix
  6270. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6271. */
  6272. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6273. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6274. var n = znear;
  6275. var f = zfar;
  6276. var t = 1.0 / (Math.tan(fov * 0.5));
  6277. var a = isVerticalFovFixed ? (t / aspect) : t;
  6278. var b = isVerticalFovFixed ? t : (t * aspect);
  6279. var c = (f + n) / (f - n);
  6280. var d = -2.0 * f * n / (f - n);
  6281. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6282. };
  6283. /**
  6284. * Creates a right-handed perspective projection matrix
  6285. * @param fov defines the horizontal field of view
  6286. * @param aspect defines the aspect ratio
  6287. * @param znear defines the near clip plane
  6288. * @param zfar defines the far clip plane
  6289. * @returns a new matrix as a right-handed perspective projection matrix
  6290. */
  6291. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6292. var matrix = Matrix.Zero();
  6293. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6294. return matrix;
  6295. };
  6296. /**
  6297. * Stores a right-handed perspective projection into a given matrix
  6298. * @param fov defines the horizontal field of view
  6299. * @param aspect defines the aspect ratio
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @param result defines the target matrix
  6303. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6304. */
  6305. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6306. //alternatively this could be expressed as:
  6307. // m = PerspectiveFovLHToRef
  6308. // m[10] *= -1.0;
  6309. // m[11] *= -1.0;
  6310. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6311. var n = znear;
  6312. var f = zfar;
  6313. var t = 1.0 / (Math.tan(fov * 0.5));
  6314. var a = isVerticalFovFixed ? (t / aspect) : t;
  6315. var b = isVerticalFovFixed ? t : (t * aspect);
  6316. var c = -(f + n) / (f - n);
  6317. var d = -2 * f * n / (f - n);
  6318. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6319. };
  6320. /**
  6321. * Stores a perspective projection for WebVR info a given matrix
  6322. * @param fov defines the field of view
  6323. * @param znear defines the near clip plane
  6324. * @param zfar defines the far clip plane
  6325. * @param result defines the target matrix
  6326. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6327. */
  6328. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6329. if (rightHanded === void 0) { rightHanded = false; }
  6330. var rightHandedFactor = rightHanded ? -1 : 1;
  6331. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6332. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6333. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6334. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6335. var xScale = 2.0 / (leftTan + rightTan);
  6336. var yScale = 2.0 / (upTan + downTan);
  6337. result.m[0] = xScale;
  6338. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6339. result.m[5] = yScale;
  6340. result.m[6] = result.m[7] = 0.0;
  6341. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6342. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6343. result.m[10] = -zfar / (znear - zfar);
  6344. result.m[11] = 1.0 * rightHandedFactor;
  6345. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6346. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6347. result._markAsUpdated();
  6348. };
  6349. /**
  6350. * Computes a complete transformation matrix
  6351. * @param viewport defines the viewport to use
  6352. * @param world defines the world matrix
  6353. * @param view defines the view matrix
  6354. * @param projection defines the projection matrix
  6355. * @param zmin defines the near clip plane
  6356. * @param zmax defines the far clip plane
  6357. * @returns the transformation matrix
  6358. */
  6359. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6360. var cw = viewport.width;
  6361. var ch = viewport.height;
  6362. var cx = viewport.x;
  6363. var cy = viewport.y;
  6364. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6365. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6366. };
  6367. /**
  6368. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix2x2 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1],
  6375. matrix.m[4], matrix.m[5]
  6376. ]);
  6377. };
  6378. /**
  6379. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix3x3 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1], matrix.m[2],
  6386. matrix.m[4], matrix.m[5], matrix.m[6],
  6387. matrix.m[8], matrix.m[9], matrix.m[10]
  6388. ]);
  6389. };
  6390. /**
  6391. * Compute the transpose of a given matrix
  6392. * @param matrix defines the matrix to transpose
  6393. * @returns the new matrix
  6394. */
  6395. Matrix.Transpose = function (matrix) {
  6396. var result = new Matrix();
  6397. Matrix.TransposeToRef(matrix, result);
  6398. return result;
  6399. };
  6400. /**
  6401. * Compute the transpose of a matrix and store it in a target matrix
  6402. * @param matrix defines the matrix to transpose
  6403. * @param result defines the target matrix
  6404. */
  6405. Matrix.TransposeToRef = function (matrix, result) {
  6406. result.m[0] = matrix.m[0];
  6407. result.m[1] = matrix.m[4];
  6408. result.m[2] = matrix.m[8];
  6409. result.m[3] = matrix.m[12];
  6410. result.m[4] = matrix.m[1];
  6411. result.m[5] = matrix.m[5];
  6412. result.m[6] = matrix.m[9];
  6413. result.m[7] = matrix.m[13];
  6414. result.m[8] = matrix.m[2];
  6415. result.m[9] = matrix.m[6];
  6416. result.m[10] = matrix.m[10];
  6417. result.m[11] = matrix.m[14];
  6418. result.m[12] = matrix.m[3];
  6419. result.m[13] = matrix.m[7];
  6420. result.m[14] = matrix.m[11];
  6421. result.m[15] = matrix.m[15];
  6422. };
  6423. /**
  6424. * Computes a reflection matrix from a plane
  6425. * @param plane defines the reflection plane
  6426. * @returns a new matrix
  6427. */
  6428. Matrix.Reflection = function (plane) {
  6429. var matrix = new Matrix();
  6430. Matrix.ReflectionToRef(plane, matrix);
  6431. return matrix;
  6432. };
  6433. /**
  6434. * Computes a reflection matrix from a plane
  6435. * @param plane defines the reflection plane
  6436. * @param result defines the target matrix
  6437. */
  6438. Matrix.ReflectionToRef = function (plane, result) {
  6439. plane.normalize();
  6440. var x = plane.normal.x;
  6441. var y = plane.normal.y;
  6442. var z = plane.normal.z;
  6443. var temp = -2 * x;
  6444. var temp2 = -2 * y;
  6445. var temp3 = -2 * z;
  6446. result.m[0] = (temp * x) + 1;
  6447. result.m[1] = temp2 * x;
  6448. result.m[2] = temp3 * x;
  6449. result.m[3] = 0.0;
  6450. result.m[4] = temp * y;
  6451. result.m[5] = (temp2 * y) + 1;
  6452. result.m[6] = temp3 * y;
  6453. result.m[7] = 0.0;
  6454. result.m[8] = temp * z;
  6455. result.m[9] = temp2 * z;
  6456. result.m[10] = (temp3 * z) + 1;
  6457. result.m[11] = 0.0;
  6458. result.m[12] = temp * plane.d;
  6459. result.m[13] = temp2 * plane.d;
  6460. result.m[14] = temp3 * plane.d;
  6461. result.m[15] = 1.0;
  6462. result._markAsUpdated();
  6463. };
  6464. /**
  6465. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6466. * @param xaxis defines the value of the 1st axis
  6467. * @param yaxis defines the value of the 2nd axis
  6468. * @param zaxis defines the value of the 3rd axis
  6469. * @param result defines the target matrix
  6470. */
  6471. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6472. result.m[0] = xaxis.x;
  6473. result.m[1] = xaxis.y;
  6474. result.m[2] = xaxis.z;
  6475. result.m[3] = 0.0;
  6476. result.m[4] = yaxis.x;
  6477. result.m[5] = yaxis.y;
  6478. result.m[6] = yaxis.z;
  6479. result.m[7] = 0.0;
  6480. result.m[8] = zaxis.x;
  6481. result.m[9] = zaxis.y;
  6482. result.m[10] = zaxis.z;
  6483. result.m[11] = 0.0;
  6484. result.m[12] = 0.0;
  6485. result.m[13] = 0.0;
  6486. result.m[14] = 0.0;
  6487. result.m[15] = 1.0;
  6488. result._markAsUpdated();
  6489. };
  6490. /**
  6491. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6492. * @param quat defines the quaternion to use
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.FromQuaternionToRef = function (quat, result) {
  6496. var xx = quat.x * quat.x;
  6497. var yy = quat.y * quat.y;
  6498. var zz = quat.z * quat.z;
  6499. var xy = quat.x * quat.y;
  6500. var zw = quat.z * quat.w;
  6501. var zx = quat.z * quat.x;
  6502. var yw = quat.y * quat.w;
  6503. var yz = quat.y * quat.z;
  6504. var xw = quat.x * quat.w;
  6505. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6506. result.m[1] = 2.0 * (xy + zw);
  6507. result.m[2] = 2.0 * (zx - yw);
  6508. result.m[3] = 0.0;
  6509. result.m[4] = 2.0 * (xy - zw);
  6510. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6511. result.m[6] = 2.0 * (yz + xw);
  6512. result.m[7] = 0.0;
  6513. result.m[8] = 2.0 * (zx + yw);
  6514. result.m[9] = 2.0 * (yz - xw);
  6515. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6516. result.m[11] = 0.0;
  6517. result.m[12] = 0.0;
  6518. result.m[13] = 0.0;
  6519. result.m[14] = 0.0;
  6520. result.m[15] = 1.0;
  6521. result._markAsUpdated();
  6522. };
  6523. Matrix._tempQuaternion = new Quaternion();
  6524. Matrix._xAxis = Vector3.Zero();
  6525. Matrix._yAxis = Vector3.Zero();
  6526. Matrix._zAxis = Vector3.Zero();
  6527. Matrix._updateFlagSeed = 0;
  6528. Matrix._identityReadOnly = Matrix.Identity();
  6529. return Matrix;
  6530. }());
  6531. BABYLON.Matrix = Matrix;
  6532. var Plane = /** @class */ (function () {
  6533. /**
  6534. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6535. */
  6536. function Plane(a, b, c, d) {
  6537. this.normal = new Vector3(a, b, c);
  6538. this.d = d;
  6539. }
  6540. /**
  6541. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6542. */
  6543. Plane.prototype.asArray = function () {
  6544. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6545. };
  6546. // Methods
  6547. /**
  6548. * Returns a new plane copied from the current Plane.
  6549. */
  6550. Plane.prototype.clone = function () {
  6551. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6552. };
  6553. /**
  6554. * Returns the string "Plane".
  6555. */
  6556. Plane.prototype.getClassName = function () {
  6557. return "Plane";
  6558. };
  6559. /**
  6560. * Returns the Plane hash code.
  6561. */
  6562. Plane.prototype.getHashCode = function () {
  6563. var hash = this.normal.getHashCode();
  6564. hash = (hash * 397) ^ (this.d || 0);
  6565. return hash;
  6566. };
  6567. /**
  6568. * Normalize the current Plane in place.
  6569. * Returns the updated Plane.
  6570. */
  6571. Plane.prototype.normalize = function () {
  6572. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6573. var magnitude = 0.0;
  6574. if (norm !== 0) {
  6575. magnitude = 1.0 / norm;
  6576. }
  6577. this.normal.x *= magnitude;
  6578. this.normal.y *= magnitude;
  6579. this.normal.z *= magnitude;
  6580. this.d *= magnitude;
  6581. return this;
  6582. };
  6583. /**
  6584. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6585. */
  6586. Plane.prototype.transform = function (transformation) {
  6587. var transposedMatrix = Matrix.Transpose(transformation);
  6588. var x = this.normal.x;
  6589. var y = this.normal.y;
  6590. var z = this.normal.z;
  6591. var d = this.d;
  6592. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6593. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6594. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6595. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6596. return new Plane(normalX, normalY, normalZ, finalD);
  6597. };
  6598. /**
  6599. * Returns the dot product (float) of the point coordinates and the plane normal.
  6600. */
  6601. Plane.prototype.dotCoordinate = function (point) {
  6602. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6603. };
  6604. /**
  6605. * Updates the current Plane from the plane defined by the three given points.
  6606. * Returns the updated Plane.
  6607. */
  6608. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6609. var x1 = point2.x - point1.x;
  6610. var y1 = point2.y - point1.y;
  6611. var z1 = point2.z - point1.z;
  6612. var x2 = point3.x - point1.x;
  6613. var y2 = point3.y - point1.y;
  6614. var z2 = point3.z - point1.z;
  6615. var yz = (y1 * z2) - (z1 * y2);
  6616. var xz = (z1 * x2) - (x1 * z2);
  6617. var xy = (x1 * y2) - (y1 * x2);
  6618. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6619. var invPyth;
  6620. if (pyth !== 0) {
  6621. invPyth = 1.0 / pyth;
  6622. }
  6623. else {
  6624. invPyth = 0.0;
  6625. }
  6626. this.normal.x = yz * invPyth;
  6627. this.normal.y = xz * invPyth;
  6628. this.normal.z = xy * invPyth;
  6629. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6630. return this;
  6631. };
  6632. /**
  6633. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6634. */
  6635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6636. var dot = Vector3.Dot(this.normal, direction);
  6637. return (dot <= epsilon);
  6638. };
  6639. /**
  6640. * Returns the signed distance (float) from the given point to the Plane.
  6641. */
  6642. Plane.prototype.signedDistanceTo = function (point) {
  6643. return Vector3.Dot(point, this.normal) + this.d;
  6644. };
  6645. // Statics
  6646. /**
  6647. * Returns a new Plane from the given array.
  6648. */
  6649. Plane.FromArray = function (array) {
  6650. return new Plane(array[0], array[1], array[2], array[3]);
  6651. };
  6652. /**
  6653. * Returns a new Plane defined by the three given points.
  6654. */
  6655. Plane.FromPoints = function (point1, point2, point3) {
  6656. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6657. result.copyFromPoints(point1, point2, point3);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns a new Plane the normal vector to this plane at the given origin point.
  6662. * Note : the vector "normal" is updated because normalized.
  6663. */
  6664. Plane.FromPositionAndNormal = function (origin, normal) {
  6665. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6666. normal.normalize();
  6667. result.normal = normal;
  6668. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6673. */
  6674. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6675. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6676. return Vector3.Dot(point, normal) + d;
  6677. };
  6678. return Plane;
  6679. }());
  6680. BABYLON.Plane = Plane;
  6681. var Viewport = /** @class */ (function () {
  6682. /**
  6683. * Creates a Viewport object located at (x, y) and sized (width, height).
  6684. */
  6685. function Viewport(x, y, width, height) {
  6686. this.x = x;
  6687. this.y = y;
  6688. this.width = width;
  6689. this.height = height;
  6690. }
  6691. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6692. if (renderWidthOrEngine.getRenderWidth) {
  6693. var engine = renderWidthOrEngine;
  6694. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6695. }
  6696. var renderWidth = renderWidthOrEngine;
  6697. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6698. };
  6699. /**
  6700. * Returns a new Viewport copied from the current one.
  6701. */
  6702. Viewport.prototype.clone = function () {
  6703. return new Viewport(this.x, this.y, this.width, this.height);
  6704. };
  6705. return Viewport;
  6706. }());
  6707. BABYLON.Viewport = Viewport;
  6708. var Frustum = /** @class */ (function () {
  6709. function Frustum() {
  6710. }
  6711. /**
  6712. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6713. */
  6714. Frustum.GetPlanes = function (transform) {
  6715. var frustumPlanes = [];
  6716. for (var index = 0; index < 6; index++) {
  6717. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6718. }
  6719. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6720. return frustumPlanes;
  6721. };
  6722. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6723. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6724. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6725. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6726. frustumPlane.d = transform.m[15] + transform.m[14];
  6727. frustumPlane.normalize();
  6728. };
  6729. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6730. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6731. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6732. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6733. frustumPlane.d = transform.m[15] - transform.m[14];
  6734. frustumPlane.normalize();
  6735. };
  6736. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6737. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6738. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6739. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6740. frustumPlane.d = transform.m[15] + transform.m[12];
  6741. frustumPlane.normalize();
  6742. };
  6743. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6744. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6745. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6746. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6747. frustumPlane.d = transform.m[15] - transform.m[12];
  6748. frustumPlane.normalize();
  6749. };
  6750. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6751. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6752. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6753. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6754. frustumPlane.d = transform.m[15] - transform.m[13];
  6755. frustumPlane.normalize();
  6756. };
  6757. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6758. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6759. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6760. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6761. frustumPlane.d = transform.m[15] + transform.m[13];
  6762. frustumPlane.normalize();
  6763. };
  6764. /**
  6765. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6766. */
  6767. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6768. // Near
  6769. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6770. // Far
  6771. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6772. // Left
  6773. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6774. // Right
  6775. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6776. // Top
  6777. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6778. // Bottom
  6779. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6780. };
  6781. return Frustum;
  6782. }());
  6783. BABYLON.Frustum = Frustum;
  6784. /** Defines supported spaces */
  6785. var Space;
  6786. (function (Space) {
  6787. /** Local (object) space */
  6788. Space[Space["LOCAL"] = 0] = "LOCAL";
  6789. /** World space */
  6790. Space[Space["WORLD"] = 1] = "WORLD";
  6791. /** Bone space */
  6792. Space[Space["BONE"] = 2] = "BONE";
  6793. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6794. /** Defines the 3 main axes */
  6795. var Axis = /** @class */ (function () {
  6796. function Axis() {
  6797. }
  6798. /** X axis */
  6799. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6800. /** Y axis */
  6801. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6802. /** Z axis */
  6803. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6804. return Axis;
  6805. }());
  6806. BABYLON.Axis = Axis;
  6807. ;
  6808. var BezierCurve = /** @class */ (function () {
  6809. function BezierCurve() {
  6810. }
  6811. /**
  6812. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6813. */
  6814. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6815. // Extract X (which is equal to time here)
  6816. var f0 = 1 - 3 * x2 + 3 * x1;
  6817. var f1 = 3 * x2 - 6 * x1;
  6818. var f2 = 3 * x1;
  6819. var refinedT = t;
  6820. for (var i = 0; i < 5; i++) {
  6821. var refinedT2 = refinedT * refinedT;
  6822. var refinedT3 = refinedT2 * refinedT;
  6823. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6824. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6825. refinedT -= (x - t) * slope;
  6826. refinedT = Math.min(1, Math.max(0, refinedT));
  6827. }
  6828. // Resolve cubic bezier for the given x
  6829. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6830. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6831. Math.pow(refinedT, 3);
  6832. };
  6833. return BezierCurve;
  6834. }());
  6835. BABYLON.BezierCurve = BezierCurve;
  6836. /**
  6837. * Defines potential orientation for back face culling
  6838. */
  6839. var Orientation;
  6840. (function (Orientation) {
  6841. /**
  6842. * Clockwise
  6843. */
  6844. Orientation[Orientation["CW"] = 0] = "CW";
  6845. /** Counter clockwise */
  6846. Orientation[Orientation["CCW"] = 1] = "CCW";
  6847. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6848. /**
  6849. * Defines angle representation
  6850. */
  6851. var Angle = /** @class */ (function () {
  6852. /**
  6853. * Creates an Angle object of "radians" radians (float).
  6854. */
  6855. function Angle(radians) {
  6856. this._radians = radians;
  6857. if (this._radians < 0.0)
  6858. this._radians += (2.0 * Math.PI);
  6859. }
  6860. /**
  6861. * Get value in degrees
  6862. * @returns the Angle value in degrees (float)
  6863. */
  6864. Angle.prototype.degrees = function () {
  6865. return this._radians * 180.0 / Math.PI;
  6866. };
  6867. /**
  6868. * Get value in radians
  6869. * @returns the Angle value in radians (float)
  6870. */
  6871. Angle.prototype.radians = function () {
  6872. return this._radians;
  6873. };
  6874. /**
  6875. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6876. * @param a defines first vector
  6877. * @param b defines second vector
  6878. * @returns a new Angle
  6879. */
  6880. Angle.BetweenTwoPoints = function (a, b) {
  6881. var delta = b.subtract(a);
  6882. var theta = Math.atan2(delta.y, delta.x);
  6883. return new Angle(theta);
  6884. };
  6885. /**
  6886. * Gets a new Angle object from the given float in radians
  6887. * @param radians defines the angle value in radians
  6888. * @returns a new Angle
  6889. */
  6890. Angle.FromRadians = function (radians) {
  6891. return new Angle(radians);
  6892. };
  6893. /**
  6894. * Gets a new Angle object from the given float in degrees
  6895. * @param degrees defines the angle value in degrees
  6896. * @returns a new Angle
  6897. */
  6898. Angle.FromDegrees = function (degrees) {
  6899. return new Angle(degrees * Math.PI / 180.0);
  6900. };
  6901. return Angle;
  6902. }());
  6903. BABYLON.Angle = Angle;
  6904. var Arc2 = /** @class */ (function () {
  6905. /**
  6906. * Creates an Arc object from the three given points : start, middle and end.
  6907. */
  6908. function Arc2(startPoint, midPoint, endPoint) {
  6909. this.startPoint = startPoint;
  6910. this.midPoint = midPoint;
  6911. this.endPoint = endPoint;
  6912. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6913. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6914. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6915. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6916. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6917. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6918. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6919. var a1 = this.startAngle.degrees();
  6920. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6921. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6922. // angles correction
  6923. if (a2 - a1 > +180.0)
  6924. a2 -= 360.0;
  6925. if (a2 - a1 < -180.0)
  6926. a2 += 360.0;
  6927. if (a3 - a2 > +180.0)
  6928. a3 -= 360.0;
  6929. if (a3 - a2 < -180.0)
  6930. a3 += 360.0;
  6931. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6932. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6933. }
  6934. return Arc2;
  6935. }());
  6936. BABYLON.Arc2 = Arc2;
  6937. var Path2 = /** @class */ (function () {
  6938. /**
  6939. * Creates a Path2 object from the starting 2D coordinates x and y.
  6940. */
  6941. function Path2(x, y) {
  6942. this._points = new Array();
  6943. this._length = 0.0;
  6944. this.closed = false;
  6945. this._points.push(new Vector2(x, y));
  6946. }
  6947. /**
  6948. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6949. * Returns the updated Path2.
  6950. */
  6951. Path2.prototype.addLineTo = function (x, y) {
  6952. if (this.closed) {
  6953. return this;
  6954. }
  6955. var newPoint = new Vector2(x, y);
  6956. var previousPoint = this._points[this._points.length - 1];
  6957. this._points.push(newPoint);
  6958. this._length += newPoint.subtract(previousPoint).length();
  6959. return this;
  6960. };
  6961. /**
  6962. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6963. * Returns the updated Path2.
  6964. */
  6965. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6966. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var startPoint = this._points[this._points.length - 1];
  6971. var midPoint = new Vector2(midX, midY);
  6972. var endPoint = new Vector2(endX, endY);
  6973. var arc = new Arc2(startPoint, midPoint, endPoint);
  6974. var increment = arc.angle.radians() / numberOfSegments;
  6975. if (arc.orientation === Orientation.CW)
  6976. increment *= -1;
  6977. var currentAngle = arc.startAngle.radians() + increment;
  6978. for (var i = 0; i < numberOfSegments; i++) {
  6979. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6980. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6981. this.addLineTo(x, y);
  6982. currentAngle += increment;
  6983. }
  6984. return this;
  6985. };
  6986. /**
  6987. * Closes the Path2.
  6988. * Returns the Path2.
  6989. */
  6990. Path2.prototype.close = function () {
  6991. this.closed = true;
  6992. return this;
  6993. };
  6994. /**
  6995. * Returns the Path2 total length (float).
  6996. */
  6997. Path2.prototype.length = function () {
  6998. var result = this._length;
  6999. if (!this.closed) {
  7000. var lastPoint = this._points[this._points.length - 1];
  7001. var firstPoint = this._points[0];
  7002. result += (firstPoint.subtract(lastPoint).length());
  7003. }
  7004. return result;
  7005. };
  7006. /**
  7007. * Returns the Path2 internal array of points.
  7008. */
  7009. Path2.prototype.getPoints = function () {
  7010. return this._points;
  7011. };
  7012. /**
  7013. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7014. */
  7015. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7016. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7017. return Vector2.Zero();
  7018. }
  7019. var lengthPosition = normalizedLengthPosition * this.length();
  7020. var previousOffset = 0;
  7021. for (var i = 0; i < this._points.length; i++) {
  7022. var j = (i + 1) % this._points.length;
  7023. var a = this._points[i];
  7024. var b = this._points[j];
  7025. var bToA = b.subtract(a);
  7026. var nextOffset = (bToA.length() + previousOffset);
  7027. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7028. var dir = bToA.normalize();
  7029. var localOffset = lengthPosition - previousOffset;
  7030. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7031. }
  7032. previousOffset = nextOffset;
  7033. }
  7034. return Vector2.Zero();
  7035. };
  7036. /**
  7037. * Returns a new Path2 starting at the coordinates (x, y).
  7038. */
  7039. Path2.StartingAt = function (x, y) {
  7040. return new Path2(x, y);
  7041. };
  7042. return Path2;
  7043. }());
  7044. BABYLON.Path2 = Path2;
  7045. var Path3D = /** @class */ (function () {
  7046. /**
  7047. * new Path3D(path, normal, raw)
  7048. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7049. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7050. * path : an array of Vector3, the curve axis of the Path3D
  7051. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7052. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7053. */
  7054. function Path3D(path, firstNormal, raw) {
  7055. if (firstNormal === void 0) { firstNormal = null; }
  7056. this.path = path;
  7057. this._curve = new Array();
  7058. this._distances = new Array();
  7059. this._tangents = new Array();
  7060. this._normals = new Array();
  7061. this._binormals = new Array();
  7062. for (var p = 0; p < path.length; p++) {
  7063. this._curve[p] = path[p].clone(); // hard copy
  7064. }
  7065. this._raw = raw || false;
  7066. this._compute(firstNormal);
  7067. }
  7068. /**
  7069. * Returns the Path3D array of successive Vector3 designing its curve.
  7070. */
  7071. Path3D.prototype.getCurve = function () {
  7072. return this._curve;
  7073. };
  7074. /**
  7075. * Returns an array populated with tangent vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getTangents = function () {
  7078. return this._tangents;
  7079. };
  7080. /**
  7081. * Returns an array populated with normal vectors on each Path3D curve point.
  7082. */
  7083. Path3D.prototype.getNormals = function () {
  7084. return this._normals;
  7085. };
  7086. /**
  7087. * Returns an array populated with binormal vectors on each Path3D curve point.
  7088. */
  7089. Path3D.prototype.getBinormals = function () {
  7090. return this._binormals;
  7091. };
  7092. /**
  7093. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7094. */
  7095. Path3D.prototype.getDistances = function () {
  7096. return this._distances;
  7097. };
  7098. /**
  7099. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7100. * Returns the same object updated.
  7101. */
  7102. Path3D.prototype.update = function (path, firstNormal) {
  7103. if (firstNormal === void 0) { firstNormal = null; }
  7104. for (var p = 0; p < path.length; p++) {
  7105. this._curve[p].x = path[p].x;
  7106. this._curve[p].y = path[p].y;
  7107. this._curve[p].z = path[p].z;
  7108. }
  7109. this._compute(firstNormal);
  7110. return this;
  7111. };
  7112. // private function compute() : computes tangents, normals and binormals
  7113. Path3D.prototype._compute = function (firstNormal) {
  7114. var l = this._curve.length;
  7115. // first and last tangents
  7116. this._tangents[0] = this._getFirstNonNullVector(0);
  7117. if (!this._raw) {
  7118. this._tangents[0].normalize();
  7119. }
  7120. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7121. if (!this._raw) {
  7122. this._tangents[l - 1].normalize();
  7123. }
  7124. // normals and binormals at first point : arbitrary vector with _normalVector()
  7125. var tg0 = this._tangents[0];
  7126. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7127. this._normals[0] = pp0;
  7128. if (!this._raw) {
  7129. this._normals[0].normalize();
  7130. }
  7131. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7132. if (!this._raw) {
  7133. this._binormals[0].normalize();
  7134. }
  7135. this._distances[0] = 0.0;
  7136. // normals and binormals : next points
  7137. var prev; // previous vector (segment)
  7138. var cur; // current vector (segment)
  7139. var curTang; // current tangent
  7140. // previous normal
  7141. var prevBinor; // previous binormal
  7142. for (var i = 1; i < l; i++) {
  7143. // tangents
  7144. prev = this._getLastNonNullVector(i);
  7145. if (i < l - 1) {
  7146. cur = this._getFirstNonNullVector(i);
  7147. this._tangents[i] = prev.add(cur);
  7148. this._tangents[i].normalize();
  7149. }
  7150. this._distances[i] = this._distances[i - 1] + prev.length();
  7151. // normals and binormals
  7152. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7153. curTang = this._tangents[i];
  7154. prevBinor = this._binormals[i - 1];
  7155. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7156. if (!this._raw) {
  7157. this._normals[i].normalize();
  7158. }
  7159. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7160. if (!this._raw) {
  7161. this._binormals[i].normalize();
  7162. }
  7163. }
  7164. };
  7165. // private function getFirstNonNullVector(index)
  7166. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7167. Path3D.prototype._getFirstNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7170. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7171. i++;
  7172. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7173. }
  7174. return nNVector;
  7175. };
  7176. // private function getLastNonNullVector(index)
  7177. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7178. Path3D.prototype._getLastNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7181. while (nLVector.length() === 0 && index > i + 1) {
  7182. i++;
  7183. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7184. }
  7185. return nLVector;
  7186. };
  7187. // private function normalVector(v0, vt, va) :
  7188. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7189. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7190. Path3D.prototype._normalVector = function (v0, vt, va) {
  7191. var normal0;
  7192. var tgl = vt.length();
  7193. if (tgl === 0.0) {
  7194. tgl = 1.0;
  7195. }
  7196. if (va === undefined || va === null) {
  7197. var point;
  7198. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7199. point = new Vector3(0.0, -1.0, 0.0);
  7200. }
  7201. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7202. point = new Vector3(1.0, 0.0, 0.0);
  7203. }
  7204. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7205. point = new Vector3(0.0, 0.0, 1.0);
  7206. }
  7207. else {
  7208. point = Vector3.Zero();
  7209. }
  7210. normal0 = Vector3.Cross(vt, point);
  7211. }
  7212. else {
  7213. normal0 = Vector3.Cross(vt, va);
  7214. Vector3.CrossToRef(normal0, vt, normal0);
  7215. }
  7216. normal0.normalize();
  7217. return normal0;
  7218. };
  7219. return Path3D;
  7220. }());
  7221. BABYLON.Path3D = Path3D;
  7222. var Curve3 = /** @class */ (function () {
  7223. /**
  7224. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7225. * A Curve3 is designed from a series of successive Vector3.
  7226. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7227. */
  7228. function Curve3(points) {
  7229. this._length = 0.0;
  7230. this._points = points;
  7231. this._length = this._computeLength(points);
  7232. }
  7233. /**
  7234. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7235. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7236. * @param v1 (Vector3) the control point
  7237. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7238. * @param nbPoints (integer) the wanted number of points in the curve
  7239. */
  7240. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7241. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7242. var bez = new Array();
  7243. var equation = function (t, val0, val1, val2) {
  7244. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7245. return res;
  7246. };
  7247. for (var i = 0; i <= nbPoints; i++) {
  7248. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7249. }
  7250. return new Curve3(bez);
  7251. };
  7252. /**
  7253. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7254. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7255. * @param v1 (Vector3) the first control point
  7256. * @param v2 (Vector3) the second control point
  7257. * @param v3 (Vector3) the end point of the Cubic Bezier
  7258. * @param nbPoints (integer) the wanted number of points in the curve
  7259. */
  7260. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7261. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7262. var bez = new Array();
  7263. var equation = function (t, val0, val1, val2, val3) {
  7264. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7265. return res;
  7266. };
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7269. }
  7270. return new Curve3(bez);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7274. * @param p1 (Vector3) the origin point of the Hermite Spline
  7275. * @param t1 (Vector3) the tangent vector at the origin point
  7276. * @param p2 (Vector3) the end point of the Hermite Spline
  7277. * @param t2 (Vector3) the tangent vector at the end point
  7278. * @param nbPoints (integer) the wanted number of points in the curve
  7279. */
  7280. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7281. var hermite = new Array();
  7282. var step = 1.0 / nbPoints;
  7283. for (var i = 0; i <= nbPoints; i++) {
  7284. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7285. }
  7286. return new Curve3(hermite);
  7287. };
  7288. /**
  7289. * Returns a Curve3 object along a CatmullRom Spline curve :
  7290. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7291. * @param nbPoints (integer) the wanted number of points between each curve control points
  7292. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7293. */
  7294. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7295. var catmullRom = new Array();
  7296. var step = 1.0 / nbPoints;
  7297. var amount = 0.0;
  7298. if (closed) {
  7299. var pointsCount = points.length;
  7300. for (var i = 0; i < pointsCount; i++) {
  7301. amount = 0;
  7302. for (var c = 0; c < nbPoints; c++) {
  7303. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7304. amount += step;
  7305. }
  7306. }
  7307. catmullRom.push(catmullRom[0]);
  7308. }
  7309. else {
  7310. var totalPoints = new Array();
  7311. totalPoints.push(points[0].clone());
  7312. Array.prototype.push.apply(totalPoints, points);
  7313. totalPoints.push(points[points.length - 1].clone());
  7314. for (var i = 0; i < totalPoints.length - 3; i++) {
  7315. amount = 0;
  7316. for (var c = 0; c < nbPoints; c++) {
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. amount += step;
  7319. }
  7320. }
  7321. i--;
  7322. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7323. }
  7324. return new Curve3(catmullRom);
  7325. };
  7326. /**
  7327. * Returns the Curve3 stored array of successive Vector3
  7328. */
  7329. Curve3.prototype.getPoints = function () {
  7330. return this._points;
  7331. };
  7332. /**
  7333. * Returns the computed length (float) of the curve.
  7334. */
  7335. Curve3.prototype.length = function () {
  7336. return this._length;
  7337. };
  7338. /**
  7339. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7340. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7341. * curveA and curveB keep unchanged.
  7342. */
  7343. Curve3.prototype.continue = function (curve) {
  7344. var lastPoint = this._points[this._points.length - 1];
  7345. var continuedPoints = this._points.slice();
  7346. var curvePoints = curve.getPoints();
  7347. for (var i = 1; i < curvePoints.length; i++) {
  7348. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7349. }
  7350. var continuedCurve = new Curve3(continuedPoints);
  7351. return continuedCurve;
  7352. };
  7353. Curve3.prototype._computeLength = function (path) {
  7354. var l = 0;
  7355. for (var i = 1; i < path.length; i++) {
  7356. l += (path[i].subtract(path[i - 1])).length();
  7357. }
  7358. return l;
  7359. };
  7360. return Curve3;
  7361. }());
  7362. BABYLON.Curve3 = Curve3;
  7363. // Vertex formats
  7364. var PositionNormalVertex = /** @class */ (function () {
  7365. function PositionNormalVertex(position, normal) {
  7366. if (position === void 0) { position = Vector3.Zero(); }
  7367. if (normal === void 0) { normal = Vector3.Up(); }
  7368. this.position = position;
  7369. this.normal = normal;
  7370. }
  7371. PositionNormalVertex.prototype.clone = function () {
  7372. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7373. };
  7374. return PositionNormalVertex;
  7375. }());
  7376. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7377. var PositionNormalTextureVertex = /** @class */ (function () {
  7378. function PositionNormalTextureVertex(position, normal, uv) {
  7379. if (position === void 0) { position = Vector3.Zero(); }
  7380. if (normal === void 0) { normal = Vector3.Up(); }
  7381. if (uv === void 0) { uv = Vector2.Zero(); }
  7382. this.position = position;
  7383. this.normal = normal;
  7384. this.uv = uv;
  7385. }
  7386. PositionNormalTextureVertex.prototype.clone = function () {
  7387. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7388. };
  7389. return PositionNormalTextureVertex;
  7390. }());
  7391. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7392. // Temporary pre-allocated objects for engine internal use
  7393. // usage in any internal function :
  7394. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7395. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7396. var Tmp = /** @class */ (function () {
  7397. function Tmp() {
  7398. }
  7399. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7400. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7401. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7402. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7403. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7404. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7405. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7406. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7407. Matrix.Zero(), Matrix.Zero(),
  7408. Matrix.Zero(), Matrix.Zero(),
  7409. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7410. return Tmp;
  7411. }());
  7412. BABYLON.Tmp = Tmp;
  7413. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7414. var MathTmp = /** @class */ (function () {
  7415. function MathTmp() {
  7416. }
  7417. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7418. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7419. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7420. return MathTmp;
  7421. }());
  7422. })(BABYLON || (BABYLON = {}));
  7423. //# sourceMappingURL=babylon.math.js.map
  7424. var BABYLON;
  7425. (function (BABYLON) {
  7426. var Scalar = /** @class */ (function () {
  7427. function Scalar() {
  7428. }
  7429. /**
  7430. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7431. */
  7432. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7433. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7434. var num = a - b;
  7435. return -epsilon <= num && num <= epsilon;
  7436. };
  7437. /**
  7438. * Returns a string : the upper case translation of the number i to hexadecimal.
  7439. */
  7440. Scalar.ToHex = function (i) {
  7441. var str = i.toString(16);
  7442. if (i <= 15) {
  7443. return ("0" + str).toUpperCase();
  7444. }
  7445. return str.toUpperCase();
  7446. };
  7447. /**
  7448. * Returns -1 if value is negative and +1 is value is positive.
  7449. * Returns the value itself if it's equal to zero.
  7450. */
  7451. Scalar.Sign = function (value) {
  7452. value = +value; // convert to a number
  7453. if (value === 0 || isNaN(value))
  7454. return value;
  7455. return value > 0 ? 1 : -1;
  7456. };
  7457. /**
  7458. * Returns the value itself if it's between min and max.
  7459. * Returns min if the value is lower than min.
  7460. * Returns max if the value is greater than max.
  7461. */
  7462. Scalar.Clamp = function (value, min, max) {
  7463. if (min === void 0) { min = 0; }
  7464. if (max === void 0) { max = 1; }
  7465. return Math.min(max, Math.max(min, value));
  7466. };
  7467. /**
  7468. * Returns the log2 of value.
  7469. */
  7470. Scalar.Log2 = function (value) {
  7471. return Math.log(value) * Math.LOG2E;
  7472. };
  7473. /**
  7474. * Loops the value, so that it is never larger than length and never smaller than 0.
  7475. *
  7476. * This is similar to the modulo operator but it works with floating point numbers.
  7477. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7478. * With t = 5 and length = 2.5, the result would be 0.0.
  7479. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7480. */
  7481. Scalar.Repeat = function (value, length) {
  7482. return value - Math.floor(value / length) * length;
  7483. };
  7484. /**
  7485. * Normalize the value between 0.0 and 1.0 using min and max values
  7486. */
  7487. Scalar.Normalize = function (value, min, max) {
  7488. return (value - min) / (max - min);
  7489. };
  7490. /**
  7491. * Denormalize the value from 0.0 and 1.0 using min and max values
  7492. */
  7493. Scalar.Denormalize = function (normalized, min, max) {
  7494. return (normalized * (max - min) + min);
  7495. };
  7496. /**
  7497. * Calculates the shortest difference between two given angles given in degrees.
  7498. */
  7499. Scalar.DeltaAngle = function (current, target) {
  7500. var num = Scalar.Repeat(target - current, 360.0);
  7501. if (num > 180.0) {
  7502. num -= 360.0;
  7503. }
  7504. return num;
  7505. };
  7506. /**
  7507. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7508. *
  7509. * The returned value will move back and forth between 0 and length
  7510. */
  7511. Scalar.PingPong = function (tx, length) {
  7512. var t = Scalar.Repeat(tx, length * 2.0);
  7513. return length - Math.abs(t - length);
  7514. };
  7515. /**
  7516. * Interpolates between min and max with smoothing at the limits.
  7517. *
  7518. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7519. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7520. */
  7521. Scalar.SmoothStep = function (from, to, tx) {
  7522. var t = Scalar.Clamp(tx);
  7523. t = -2.0 * t * t * t + 3.0 * t * t;
  7524. return to * t + from * (1.0 - t);
  7525. };
  7526. /**
  7527. * Moves a value current towards target.
  7528. *
  7529. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7530. * Negative values of maxDelta pushes the value away from target.
  7531. */
  7532. Scalar.MoveTowards = function (current, target, maxDelta) {
  7533. var result = 0;
  7534. if (Math.abs(target - current) <= maxDelta) {
  7535. result = target;
  7536. }
  7537. else {
  7538. result = current + Scalar.Sign(target - current) * maxDelta;
  7539. }
  7540. return result;
  7541. };
  7542. /**
  7543. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7544. *
  7545. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7546. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7547. */
  7548. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7549. var num = Scalar.DeltaAngle(current, target);
  7550. var result = 0;
  7551. if (-maxDelta < num && num < maxDelta) {
  7552. result = target;
  7553. }
  7554. else {
  7555. target = current + num;
  7556. result = Scalar.MoveTowards(current, target, maxDelta);
  7557. }
  7558. return result;
  7559. };
  7560. /**
  7561. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7562. */
  7563. Scalar.Lerp = function (start, end, amount) {
  7564. return start + ((end - start) * amount);
  7565. };
  7566. /**
  7567. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7568. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7569. */
  7570. Scalar.LerpAngle = function (start, end, amount) {
  7571. var num = Scalar.Repeat(end - start, 360.0);
  7572. if (num > 180.0) {
  7573. num -= 360.0;
  7574. }
  7575. return start + num * Scalar.Clamp(amount);
  7576. };
  7577. /**
  7578. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7579. */
  7580. Scalar.InverseLerp = function (a, b, value) {
  7581. var result = 0;
  7582. if (a != b) {
  7583. result = Scalar.Clamp((value - a) / (b - a));
  7584. }
  7585. else {
  7586. result = 0.0;
  7587. }
  7588. return result;
  7589. };
  7590. /**
  7591. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7592. */
  7593. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7594. var squared = amount * amount;
  7595. var cubed = amount * squared;
  7596. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7597. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7598. var part3 = (cubed - (2.0 * squared)) + amount;
  7599. var part4 = cubed - squared;
  7600. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7601. };
  7602. /**
  7603. * Returns a random float number between and min and max values
  7604. */
  7605. Scalar.RandomRange = function (min, max) {
  7606. if (min === max)
  7607. return min;
  7608. return ((Math.random() * (max - min)) + min);
  7609. };
  7610. /**
  7611. * This function returns percentage of a number in a given range.
  7612. *
  7613. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7614. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7615. */
  7616. Scalar.RangeToPercent = function (number, min, max) {
  7617. return ((number - min) / (max - min));
  7618. };
  7619. /**
  7620. * This function returns number that corresponds to the percentage in a given range.
  7621. *
  7622. * PercentToRange(0.34,0,100) will return 34.
  7623. */
  7624. Scalar.PercentToRange = function (percent, min, max) {
  7625. return ((max - min) * percent + min);
  7626. };
  7627. /**
  7628. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7629. * @param angle The angle to normalize in radian.
  7630. * @return The converted angle.
  7631. */
  7632. Scalar.NormalizeRadians = function (angle) {
  7633. // More precise but slower version kept for reference.
  7634. // angle = angle % Tools.TwoPi;
  7635. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7636. //if (angle > Math.PI) {
  7637. // angle -= Tools.TwoPi;
  7638. //}
  7639. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7640. return angle;
  7641. };
  7642. /**
  7643. * Two pi constants convenient for computation.
  7644. */
  7645. Scalar.TwoPi = Math.PI * 2;
  7646. return Scalar;
  7647. }());
  7648. BABYLON.Scalar = Scalar;
  7649. })(BABYLON || (BABYLON = {}));
  7650. //# sourceMappingURL=babylon.math.scalar.js.map
  7651. //# sourceMappingURL=babylon.mixins.js.map
  7652. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7653. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7654. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7655. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7656. //# sourceMappingURL=babylon.webgl2.js.map
  7657. var BABYLON;
  7658. (function (BABYLON) {
  7659. var __decoratorInitialStore = {};
  7660. var __mergedStore = {};
  7661. var _copySource = function (creationFunction, source, instanciate) {
  7662. var destination = creationFunction();
  7663. // Tags
  7664. if (BABYLON.Tags) {
  7665. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7666. }
  7667. var classStore = getMergedStore(destination);
  7668. // Properties
  7669. for (var property in classStore) {
  7670. var propertyDescriptor = classStore[property];
  7671. var sourceProperty = source[property];
  7672. var propertyType = propertyDescriptor.type;
  7673. if (sourceProperty !== undefined && sourceProperty !== null) {
  7674. switch (propertyType) {
  7675. case 0: // Value
  7676. case 6: // Mesh reference
  7677. case 11: // Camera reference
  7678. destination[property] = sourceProperty;
  7679. break;
  7680. case 1: // Texture
  7681. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7682. break;
  7683. case 2: // Color3
  7684. case 3: // FresnelParameters
  7685. case 4: // Vector2
  7686. case 5: // Vector3
  7687. case 7: // Color Curves
  7688. case 10: // Quaternion
  7689. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7690. break;
  7691. }
  7692. }
  7693. }
  7694. return destination;
  7695. };
  7696. function getDirectStore(target) {
  7697. var classKey = target.getClassName();
  7698. if (!__decoratorInitialStore[classKey]) {
  7699. __decoratorInitialStore[classKey] = {};
  7700. }
  7701. return __decoratorInitialStore[classKey];
  7702. }
  7703. /**
  7704. * Return the list of properties flagged as serializable
  7705. * @param target: host object
  7706. */
  7707. function getMergedStore(target) {
  7708. var classKey = target.getClassName();
  7709. if (__mergedStore[classKey]) {
  7710. return __mergedStore[classKey];
  7711. }
  7712. __mergedStore[classKey] = {};
  7713. var store = __mergedStore[classKey];
  7714. var currentTarget = target;
  7715. var currentKey = classKey;
  7716. while (currentKey) {
  7717. var initialStore = __decoratorInitialStore[currentKey];
  7718. for (var property in initialStore) {
  7719. store[property] = initialStore[property];
  7720. }
  7721. var parent_1 = void 0;
  7722. var done = false;
  7723. do {
  7724. parent_1 = Object.getPrototypeOf(currentTarget);
  7725. if (!parent_1.getClassName) {
  7726. done = true;
  7727. break;
  7728. }
  7729. if (parent_1.getClassName() !== currentKey) {
  7730. break;
  7731. }
  7732. currentTarget = parent_1;
  7733. } while (parent_1);
  7734. if (done) {
  7735. break;
  7736. }
  7737. currentKey = parent_1.getClassName();
  7738. currentTarget = parent_1;
  7739. }
  7740. return store;
  7741. }
  7742. function generateSerializableMember(type, sourceName) {
  7743. return function (target, propertyKey) {
  7744. var classStore = getDirectStore(target);
  7745. if (!classStore[propertyKey]) {
  7746. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7747. }
  7748. };
  7749. }
  7750. function generateExpandMember(setCallback, targetKey) {
  7751. if (targetKey === void 0) { targetKey = null; }
  7752. return function (target, propertyKey) {
  7753. var key = targetKey || ("_" + propertyKey);
  7754. Object.defineProperty(target, propertyKey, {
  7755. get: function () {
  7756. return this[key];
  7757. },
  7758. set: function (value) {
  7759. if (this[key] === value) {
  7760. return;
  7761. }
  7762. this[key] = value;
  7763. target[setCallback].apply(this);
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. };
  7769. }
  7770. function expandToProperty(callback, targetKey) {
  7771. if (targetKey === void 0) { targetKey = null; }
  7772. return generateExpandMember(callback, targetKey);
  7773. }
  7774. BABYLON.expandToProperty = expandToProperty;
  7775. function serialize(sourceName) {
  7776. return generateSerializableMember(0, sourceName); // value member
  7777. }
  7778. BABYLON.serialize = serialize;
  7779. function serializeAsTexture(sourceName) {
  7780. return generateSerializableMember(1, sourceName); // texture member
  7781. }
  7782. BABYLON.serializeAsTexture = serializeAsTexture;
  7783. function serializeAsColor3(sourceName) {
  7784. return generateSerializableMember(2, sourceName); // color3 member
  7785. }
  7786. BABYLON.serializeAsColor3 = serializeAsColor3;
  7787. function serializeAsFresnelParameters(sourceName) {
  7788. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7789. }
  7790. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7791. function serializeAsVector2(sourceName) {
  7792. return generateSerializableMember(4, sourceName); // vector2 member
  7793. }
  7794. BABYLON.serializeAsVector2 = serializeAsVector2;
  7795. function serializeAsVector3(sourceName) {
  7796. return generateSerializableMember(5, sourceName); // vector3 member
  7797. }
  7798. BABYLON.serializeAsVector3 = serializeAsVector3;
  7799. function serializeAsMeshReference(sourceName) {
  7800. return generateSerializableMember(6, sourceName); // mesh reference member
  7801. }
  7802. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7803. function serializeAsColorCurves(sourceName) {
  7804. return generateSerializableMember(7, sourceName); // color curves
  7805. }
  7806. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7807. function serializeAsColor4(sourceName) {
  7808. return generateSerializableMember(8, sourceName); // color 4
  7809. }
  7810. BABYLON.serializeAsColor4 = serializeAsColor4;
  7811. function serializeAsImageProcessingConfiguration(sourceName) {
  7812. return generateSerializableMember(9, sourceName); // image processing
  7813. }
  7814. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7815. function serializeAsQuaternion(sourceName) {
  7816. return generateSerializableMember(10, sourceName); // quaternion member
  7817. }
  7818. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7819. /**
  7820. * Decorator used to define property that can be serialized as reference to a camera
  7821. * @param sourceName defines the name of the property to decorate
  7822. */
  7823. function serializeAsCameraReference(sourceName) {
  7824. return generateSerializableMember(11, sourceName); // camera reference member
  7825. }
  7826. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7827. var SerializationHelper = /** @class */ (function () {
  7828. function SerializationHelper() {
  7829. }
  7830. SerializationHelper.Serialize = function (entity, serializationObject) {
  7831. if (!serializationObject) {
  7832. serializationObject = {};
  7833. }
  7834. // Tags
  7835. if (BABYLON.Tags) {
  7836. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7837. }
  7838. var serializedProperties = getMergedStore(entity);
  7839. // Properties
  7840. for (var property in serializedProperties) {
  7841. var propertyDescriptor = serializedProperties[property];
  7842. var targetPropertyName = propertyDescriptor.sourceName || property;
  7843. var propertyType = propertyDescriptor.type;
  7844. var sourceProperty = entity[property];
  7845. if (sourceProperty !== undefined && sourceProperty !== null) {
  7846. switch (propertyType) {
  7847. case 0: // Value
  7848. serializationObject[targetPropertyName] = sourceProperty;
  7849. break;
  7850. case 1: // Texture
  7851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7852. break;
  7853. case 2: // Color3
  7854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7855. break;
  7856. case 3: // FresnelParameters
  7857. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7858. break;
  7859. case 4: // Vector2
  7860. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7861. break;
  7862. case 5: // Vector3
  7863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7864. break;
  7865. case 6: // Mesh reference
  7866. serializationObject[targetPropertyName] = sourceProperty.id;
  7867. break;
  7868. case 7: // Color Curves
  7869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7870. break;
  7871. case 8: // Color 4
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 9: // Image Processing
  7875. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7876. break;
  7877. case 10: // Quaternion
  7878. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7879. break;
  7880. case 11: // Camera reference
  7881. serializationObject[targetPropertyName] = sourceProperty.id;
  7882. break;
  7883. }
  7884. }
  7885. }
  7886. return serializationObject;
  7887. };
  7888. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7889. if (rootUrl === void 0) { rootUrl = null; }
  7890. var destination = creationFunction();
  7891. if (!rootUrl) {
  7892. rootUrl = "";
  7893. }
  7894. // Tags
  7895. if (BABYLON.Tags) {
  7896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7897. }
  7898. var classStore = getMergedStore(destination);
  7899. // Properties
  7900. for (var property in classStore) {
  7901. var propertyDescriptor = classStore[property];
  7902. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7903. var propertyType = propertyDescriptor.type;
  7904. if (sourceProperty !== undefined && sourceProperty !== null) {
  7905. var dest = destination;
  7906. switch (propertyType) {
  7907. case 0: // Value
  7908. dest[property] = sourceProperty;
  7909. break;
  7910. case 1: // Texture
  7911. if (scene) {
  7912. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7913. }
  7914. break;
  7915. case 2: // Color3
  7916. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7917. break;
  7918. case 3: // FresnelParameters
  7919. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7920. break;
  7921. case 4: // Vector2
  7922. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7923. break;
  7924. case 5: // Vector3
  7925. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7926. break;
  7927. case 6: // Mesh reference
  7928. if (scene) {
  7929. dest[property] = scene.getLastMeshByID(sourceProperty);
  7930. }
  7931. break;
  7932. case 7: // Color Curves
  7933. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7934. break;
  7935. case 8: // Color 4
  7936. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7937. break;
  7938. case 9: // Image Processing
  7939. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7940. break;
  7941. case 10: // Quaternion
  7942. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7943. break;
  7944. case 11: // Camera reference
  7945. if (scene) {
  7946. dest[property] = scene.getCameraByID(sourceProperty);
  7947. }
  7948. break;
  7949. }
  7950. }
  7951. }
  7952. return destination;
  7953. };
  7954. SerializationHelper.Clone = function (creationFunction, source) {
  7955. return _copySource(creationFunction, source, false);
  7956. };
  7957. SerializationHelper.Instanciate = function (creationFunction, source) {
  7958. return _copySource(creationFunction, source, true);
  7959. };
  7960. return SerializationHelper;
  7961. }());
  7962. BABYLON.SerializationHelper = SerializationHelper;
  7963. })(BABYLON || (BABYLON = {}));
  7964. //# sourceMappingURL=babylon.decorators.js.map
  7965. var BABYLON;
  7966. (function (BABYLON) {
  7967. /**
  7968. * Wrapper class for promise with external resolve and reject.
  7969. */
  7970. var Deferred = /** @class */ (function () {
  7971. /**
  7972. * Constructor for this deferred object.
  7973. */
  7974. function Deferred() {
  7975. var _this = this;
  7976. this.promise = new Promise(function (resolve, reject) {
  7977. _this._resolve = resolve;
  7978. _this._reject = reject;
  7979. });
  7980. }
  7981. Object.defineProperty(Deferred.prototype, "resolve", {
  7982. /**
  7983. * The resolve method of the promise associated with this deferred object.
  7984. */
  7985. get: function () {
  7986. return this._resolve;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Deferred.prototype, "reject", {
  7992. /**
  7993. * The reject method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._reject;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. return Deferred;
  8002. }());
  8003. BABYLON.Deferred = Deferred;
  8004. })(BABYLON || (BABYLON = {}));
  8005. //# sourceMappingURL=babylon.deferred.js.map
  8006. var BABYLON;
  8007. (function (BABYLON) {
  8008. /**
  8009. * A class serves as a medium between the observable and its observers
  8010. */
  8011. var EventState = /** @class */ (function () {
  8012. /**
  8013. * Create a new EventState
  8014. * @param mask defines the mask associated with this state
  8015. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8016. * @param target defines the original target of the state
  8017. * @param currentTarget defines the current target of the state
  8018. */
  8019. function EventState(mask, skipNextObservers, target, currentTarget) {
  8020. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8021. this.initalize(mask, skipNextObservers, target, currentTarget);
  8022. }
  8023. /**
  8024. * Initialize the current event state
  8025. * @param mask defines the mask associated with this state
  8026. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8027. * @param target defines the original target of the state
  8028. * @param currentTarget defines the current target of the state
  8029. * @returns the current event state
  8030. */
  8031. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8032. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8033. this.mask = mask;
  8034. this.skipNextObservers = skipNextObservers;
  8035. this.target = target;
  8036. this.currentTarget = currentTarget;
  8037. return this;
  8038. };
  8039. return EventState;
  8040. }());
  8041. BABYLON.EventState = EventState;
  8042. /**
  8043. * Represent an Observer registered to a given Observable object.
  8044. */
  8045. var Observer = /** @class */ (function () {
  8046. /**
  8047. * Creates a new observer
  8048. * @param callback defines the callback to call when the observer is notified
  8049. * @param mask defines the mask of the observer (used to filter notifications)
  8050. * @param scope defines the current scope used to restore the JS context
  8051. */
  8052. function Observer(
  8053. /**
  8054. * Defines the callback to call when the observer is notified
  8055. */
  8056. callback,
  8057. /**
  8058. * Defines the mask of the observer (used to filter notifications)
  8059. */
  8060. mask,
  8061. /**
  8062. * Defines the current scope used to restore the JS context
  8063. */
  8064. scope) {
  8065. if (scope === void 0) { scope = null; }
  8066. this.callback = callback;
  8067. this.mask = mask;
  8068. this.scope = scope;
  8069. /** @hidden */
  8070. this._willBeUnregistered = false;
  8071. /**
  8072. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8073. */
  8074. this.unregisterOnNextCall = false;
  8075. }
  8076. return Observer;
  8077. }());
  8078. BABYLON.Observer = Observer;
  8079. /**
  8080. * Represent a list of observers registered to multiple Observables object.
  8081. */
  8082. var MultiObserver = /** @class */ (function () {
  8083. function MultiObserver() {
  8084. }
  8085. /**
  8086. * Release associated resources
  8087. */
  8088. MultiObserver.prototype.dispose = function () {
  8089. if (this._observers && this._observables) {
  8090. for (var index = 0; index < this._observers.length; index++) {
  8091. this._observables[index].remove(this._observers[index]);
  8092. }
  8093. }
  8094. this._observers = null;
  8095. this._observables = null;
  8096. };
  8097. /**
  8098. * Raise a callback when one of the observable will notify
  8099. * @param observables defines a list of observables to watch
  8100. * @param callback defines the callback to call on notification
  8101. * @param mask defines the mask used to filter notifications
  8102. * @param scope defines the current scope used to restore the JS context
  8103. * @returns the new MultiObserver
  8104. */
  8105. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8106. if (mask === void 0) { mask = -1; }
  8107. if (scope === void 0) { scope = null; }
  8108. var result = new MultiObserver();
  8109. result._observers = new Array();
  8110. result._observables = observables;
  8111. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8112. var observable = observables_1[_i];
  8113. var observer = observable.add(callback, mask, false, scope);
  8114. if (observer) {
  8115. result._observers.push(observer);
  8116. }
  8117. }
  8118. return result;
  8119. };
  8120. return MultiObserver;
  8121. }());
  8122. BABYLON.MultiObserver = MultiObserver;
  8123. /**
  8124. * The Observable class is a simple implementation of the Observable pattern.
  8125. *
  8126. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8127. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8128. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8129. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8130. */
  8131. var Observable = /** @class */ (function () {
  8132. /**
  8133. * Creates a new observable
  8134. * @param onObserverAdded defines a callback to call when a new observer is added
  8135. */
  8136. function Observable(onObserverAdded) {
  8137. this._observers = new Array();
  8138. this._eventState = new EventState(0);
  8139. if (onObserverAdded) {
  8140. this._onObserverAdded = onObserverAdded;
  8141. }
  8142. }
  8143. /**
  8144. * Create a new Observer with the specified callback
  8145. * @param callback the callback that will be executed for that Observer
  8146. * @param mask the mask used to filter observers
  8147. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8148. * @param scope optional scope for the callback to be called from
  8149. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8150. * @returns the new observer created for the callback
  8151. */
  8152. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8153. if (mask === void 0) { mask = -1; }
  8154. if (insertFirst === void 0) { insertFirst = false; }
  8155. if (scope === void 0) { scope = null; }
  8156. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8157. if (!callback) {
  8158. return null;
  8159. }
  8160. var observer = new Observer(callback, mask, scope);
  8161. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8162. if (insertFirst) {
  8163. this._observers.unshift(observer);
  8164. }
  8165. else {
  8166. this._observers.push(observer);
  8167. }
  8168. if (this._onObserverAdded) {
  8169. this._onObserverAdded(observer);
  8170. }
  8171. return observer;
  8172. };
  8173. /**
  8174. * Create a new Observer with the specified callback and unregisters after the next notification
  8175. * @param callback the callback that will be executed for that Observer
  8176. * @returns the new observer created for the callback
  8177. */
  8178. Observable.prototype.addOnce = function (callback) {
  8179. return this.add(callback, undefined, undefined, undefined, true);
  8180. };
  8181. /**
  8182. * Remove an Observer from the Observable object
  8183. * @param observer the instance of the Observer to remove
  8184. * @returns false if it doesn't belong to this Observable
  8185. */
  8186. Observable.prototype.remove = function (observer) {
  8187. if (!observer) {
  8188. return false;
  8189. }
  8190. var index = this._observers.indexOf(observer);
  8191. if (index !== -1) {
  8192. this._deferUnregister(observer);
  8193. return true;
  8194. }
  8195. return false;
  8196. };
  8197. /**
  8198. * Remove a callback from the Observable object
  8199. * @param callback the callback to remove
  8200. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8201. * @returns false if it doesn't belong to this Observable
  8202. */
  8203. Observable.prototype.removeCallback = function (callback, scope) {
  8204. for (var index = 0; index < this._observers.length; index++) {
  8205. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8206. this._deferUnregister(this._observers[index]);
  8207. return true;
  8208. }
  8209. }
  8210. return false;
  8211. };
  8212. Observable.prototype._deferUnregister = function (observer) {
  8213. var _this = this;
  8214. observer.unregisterOnNextCall = false;
  8215. observer._willBeUnregistered = true;
  8216. BABYLON.Tools.SetImmediate(function () {
  8217. _this._remove(observer);
  8218. });
  8219. };
  8220. // This should only be called when not iterating over _observers to avoid callback skipping.
  8221. // Removes an observer from the _observer Array.
  8222. Observable.prototype._remove = function (observer) {
  8223. if (!observer) {
  8224. return false;
  8225. }
  8226. var index = this._observers.indexOf(observer);
  8227. if (index !== -1) {
  8228. this._observers.splice(index, 1);
  8229. return true;
  8230. }
  8231. return false;
  8232. };
  8233. /**
  8234. * Notify all Observers by calling their respective callback with the given data
  8235. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8236. * @param eventData defines the data to send to all observers
  8237. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8238. * @param target defines the original target of the state
  8239. * @param currentTarget defines the current target of the state
  8240. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8241. */
  8242. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8243. if (mask === void 0) { mask = -1; }
  8244. if (!this._observers.length) {
  8245. return true;
  8246. }
  8247. var state = this._eventState;
  8248. state.mask = mask;
  8249. state.target = target;
  8250. state.currentTarget = currentTarget;
  8251. state.skipNextObservers = false;
  8252. state.lastReturnValue = eventData;
  8253. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8254. var obs = _a[_i];
  8255. if (obs._willBeUnregistered) {
  8256. continue;
  8257. }
  8258. if (obs.mask & mask) {
  8259. if (obs.scope) {
  8260. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8261. }
  8262. else {
  8263. state.lastReturnValue = obs.callback(eventData, state);
  8264. }
  8265. if (obs.unregisterOnNextCall) {
  8266. this._deferUnregister(obs);
  8267. }
  8268. }
  8269. if (state.skipNextObservers) {
  8270. return false;
  8271. }
  8272. }
  8273. return true;
  8274. };
  8275. /**
  8276. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8277. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8278. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8279. * and it is crucial that all callbacks will be executed.
  8280. * The order of the callbacks is kept, callbacks are not executed parallel.
  8281. *
  8282. * @param eventData The data to be sent to each callback
  8283. * @param mask is used to filter observers defaults to -1
  8284. * @param target defines the callback target (see EventState)
  8285. * @param currentTarget defines he current object in the bubbling phase
  8286. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8287. */
  8288. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8289. var _this = this;
  8290. if (mask === void 0) { mask = -1; }
  8291. // create an empty promise
  8292. var p = Promise.resolve(eventData);
  8293. // no observers? return this promise.
  8294. if (!this._observers.length) {
  8295. return p;
  8296. }
  8297. var state = this._eventState;
  8298. state.mask = mask;
  8299. state.target = target;
  8300. state.currentTarget = currentTarget;
  8301. state.skipNextObservers = false;
  8302. // execute one callback after another (not using Promise.all, the order is important)
  8303. this._observers.forEach(function (obs) {
  8304. if (state.skipNextObservers) {
  8305. return;
  8306. }
  8307. if (obs._willBeUnregistered) {
  8308. return;
  8309. }
  8310. if (obs.mask & mask) {
  8311. if (obs.scope) {
  8312. p = p.then(function (lastReturnedValue) {
  8313. state.lastReturnValue = lastReturnedValue;
  8314. return obs.callback.apply(obs.scope, [eventData, state]);
  8315. });
  8316. }
  8317. else {
  8318. p = p.then(function (lastReturnedValue) {
  8319. state.lastReturnValue = lastReturnedValue;
  8320. return obs.callback(eventData, state);
  8321. });
  8322. }
  8323. if (obs.unregisterOnNextCall) {
  8324. _this._deferUnregister(obs);
  8325. }
  8326. }
  8327. });
  8328. // return the eventData
  8329. return p.then(function () { return eventData; });
  8330. };
  8331. /**
  8332. * Notify a specific observer
  8333. * @param observer defines the observer to notify
  8334. * @param eventData defines the data to be sent to each callback
  8335. * @param mask is used to filter observers defaults to -1
  8336. */
  8337. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8338. if (mask === void 0) { mask = -1; }
  8339. var state = this._eventState;
  8340. state.mask = mask;
  8341. state.skipNextObservers = false;
  8342. observer.callback(eventData, state);
  8343. };
  8344. /**
  8345. * Gets a boolean indicating if the observable has at least one observer
  8346. * @returns true is the Observable has at least one Observer registered
  8347. */
  8348. Observable.prototype.hasObservers = function () {
  8349. return this._observers.length > 0;
  8350. };
  8351. /**
  8352. * Clear the list of observers
  8353. */
  8354. Observable.prototype.clear = function () {
  8355. this._observers = new Array();
  8356. this._onObserverAdded = null;
  8357. };
  8358. /**
  8359. * Clone the current observable
  8360. * @returns a new observable
  8361. */
  8362. Observable.prototype.clone = function () {
  8363. var result = new Observable();
  8364. result._observers = this._observers.slice(0);
  8365. return result;
  8366. };
  8367. /**
  8368. * Does this observable handles observer registered with a given mask
  8369. * @param mask defines the mask to be tested
  8370. * @return whether or not one observer registered with the given mask is handeled
  8371. **/
  8372. Observable.prototype.hasSpecificMask = function (mask) {
  8373. if (mask === void 0) { mask = -1; }
  8374. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8375. var obs = _a[_i];
  8376. if (obs.mask & mask || obs.mask === mask) {
  8377. return true;
  8378. }
  8379. }
  8380. return false;
  8381. };
  8382. return Observable;
  8383. }());
  8384. BABYLON.Observable = Observable;
  8385. })(BABYLON || (BABYLON = {}));
  8386. //# sourceMappingURL=babylon.observable.js.map
  8387. var BABYLON;
  8388. (function (BABYLON) {
  8389. var SmartArray = /** @class */ (function () {
  8390. function SmartArray(capacity) {
  8391. this.length = 0;
  8392. this.data = new Array(capacity);
  8393. this._id = SmartArray._GlobalId++;
  8394. }
  8395. SmartArray.prototype.push = function (value) {
  8396. this.data[this.length++] = value;
  8397. if (this.length > this.data.length) {
  8398. this.data.length *= 2;
  8399. }
  8400. };
  8401. SmartArray.prototype.forEach = function (func) {
  8402. for (var index = 0; index < this.length; index++) {
  8403. func(this.data[index]);
  8404. }
  8405. };
  8406. SmartArray.prototype.sort = function (compareFn) {
  8407. this.data.sort(compareFn);
  8408. };
  8409. SmartArray.prototype.reset = function () {
  8410. this.length = 0;
  8411. };
  8412. SmartArray.prototype.dispose = function () {
  8413. this.reset();
  8414. if (this.data) {
  8415. this.data.length = 0;
  8416. this.data = [];
  8417. }
  8418. };
  8419. SmartArray.prototype.concat = function (array) {
  8420. if (array.length === 0) {
  8421. return;
  8422. }
  8423. if (this.length + array.length > this.data.length) {
  8424. this.data.length = (this.length + array.length) * 2;
  8425. }
  8426. for (var index = 0; index < array.length; index++) {
  8427. this.data[this.length++] = (array.data || array)[index];
  8428. }
  8429. };
  8430. SmartArray.prototype.indexOf = function (value) {
  8431. var position = this.data.indexOf(value);
  8432. if (position >= this.length) {
  8433. return -1;
  8434. }
  8435. return position;
  8436. };
  8437. SmartArray.prototype.contains = function (value) {
  8438. return this.data.indexOf(value) !== -1;
  8439. };
  8440. // Statics
  8441. SmartArray._GlobalId = 0;
  8442. return SmartArray;
  8443. }());
  8444. BABYLON.SmartArray = SmartArray;
  8445. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8446. __extends(SmartArrayNoDuplicate, _super);
  8447. function SmartArrayNoDuplicate() {
  8448. var _this = _super !== null && _super.apply(this, arguments) || this;
  8449. _this._duplicateId = 0;
  8450. return _this;
  8451. }
  8452. SmartArrayNoDuplicate.prototype.push = function (value) {
  8453. _super.prototype.push.call(this, value);
  8454. if (!value.__smartArrayFlags) {
  8455. value.__smartArrayFlags = {};
  8456. }
  8457. value.__smartArrayFlags[this._id] = this._duplicateId;
  8458. };
  8459. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8460. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8461. return false;
  8462. }
  8463. this.push(value);
  8464. return true;
  8465. };
  8466. SmartArrayNoDuplicate.prototype.reset = function () {
  8467. _super.prototype.reset.call(this);
  8468. this._duplicateId++;
  8469. };
  8470. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8471. if (array.length === 0) {
  8472. return;
  8473. }
  8474. if (this.length + array.length > this.data.length) {
  8475. this.data.length = (this.length + array.length) * 2;
  8476. }
  8477. for (var index = 0; index < array.length; index++) {
  8478. var item = (array.data || array)[index];
  8479. this.pushNoDuplicate(item);
  8480. }
  8481. };
  8482. return SmartArrayNoDuplicate;
  8483. }(SmartArray));
  8484. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8485. })(BABYLON || (BABYLON = {}));
  8486. //# sourceMappingURL=babylon.smartArray.js.map
  8487. var BABYLON;
  8488. (function (BABYLON) {
  8489. /** Class used to store color gradient */
  8490. var ColorGradient = /** @class */ (function () {
  8491. function ColorGradient() {
  8492. }
  8493. /**
  8494. * Will get a color picked randomly between color1 and color2.
  8495. * If color2 is undefined then color1 will be used
  8496. * @param result defines the target Color4 to store the result in
  8497. */
  8498. ColorGradient.prototype.getColorToRef = function (result) {
  8499. if (!this.color2) {
  8500. result.copyFrom(this.color1);
  8501. return;
  8502. }
  8503. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8504. };
  8505. return ColorGradient;
  8506. }());
  8507. BABYLON.ColorGradient = ColorGradient;
  8508. /** Class used to store factor gradient */
  8509. var FactorGradient = /** @class */ (function () {
  8510. function FactorGradient() {
  8511. }
  8512. /**
  8513. * Will get a number picked randomly between factor1 and factor2.
  8514. * If factor2 is undefined then factor1 will be used
  8515. * @returns the picked number
  8516. */
  8517. FactorGradient.prototype.getFactor = function () {
  8518. if (this.factor2 === undefined) {
  8519. return this.factor1;
  8520. }
  8521. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8522. };
  8523. return FactorGradient;
  8524. }());
  8525. BABYLON.FactorGradient = FactorGradient;
  8526. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8527. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8528. var LoadFileError = /** @class */ (function (_super) {
  8529. __extends(LoadFileError, _super);
  8530. function LoadFileError(message, request) {
  8531. var _this = _super.call(this, message) || this;
  8532. _this.request = request;
  8533. _this.name = "LoadFileError";
  8534. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8535. return _this;
  8536. }
  8537. // Polyfill for Object.setPrototypeOf if necessary.
  8538. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8539. return LoadFileError;
  8540. }(Error));
  8541. BABYLON.LoadFileError = LoadFileError;
  8542. var RetryStrategy = /** @class */ (function () {
  8543. function RetryStrategy() {
  8544. }
  8545. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8546. if (maxRetries === void 0) { maxRetries = 3; }
  8547. if (baseInterval === void 0) { baseInterval = 500; }
  8548. return function (url, request, retryIndex) {
  8549. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8550. return -1;
  8551. }
  8552. return Math.pow(2, retryIndex) * baseInterval;
  8553. };
  8554. };
  8555. return RetryStrategy;
  8556. }());
  8557. BABYLON.RetryStrategy = RetryStrategy;
  8558. // Screenshots
  8559. var screenshotCanvas;
  8560. var cloneValue = function (source, destinationObject) {
  8561. if (!source)
  8562. return null;
  8563. if (source instanceof BABYLON.Mesh) {
  8564. return null;
  8565. }
  8566. if (source instanceof BABYLON.SubMesh) {
  8567. return source.clone(destinationObject);
  8568. }
  8569. else if (source.clone) {
  8570. return source.clone();
  8571. }
  8572. return null;
  8573. };
  8574. var Tools = /** @class */ (function () {
  8575. function Tools() {
  8576. }
  8577. /**
  8578. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8579. * @param u defines the coordinate on X axis
  8580. * @param v defines the coordinate on Y axis
  8581. * @param width defines the width of the source data
  8582. * @param height defines the height of the source data
  8583. * @param pixels defines the source byte array
  8584. * @param color defines the output color
  8585. */
  8586. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8587. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8588. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8589. var position = (wrappedU + wrappedV * width) * 4;
  8590. color.r = pixels[position] / 255;
  8591. color.g = pixels[position + 1] / 255;
  8592. color.b = pixels[position + 2] / 255;
  8593. color.a = pixels[position + 3] / 255;
  8594. };
  8595. /**
  8596. * Read the R component of a byte array at a specified coordinates (taking in account wrapping)
  8597. * @param u defines the coordinate on X axis
  8598. * @param v defines the coordinate on Y axis
  8599. * @param width defines the width of the source data
  8600. * @param height defines the height of the source data
  8601. * @param pixels defines the source byte array
  8602. * @returns the R value
  8603. */
  8604. Tools.FetchR = function (u, v, width, height, pixels) {
  8605. u = Math.abs(u) + 0.5;
  8606. v = Math.abs(v) + 0.5;
  8607. var wrappedU = ((u * width) % width) | 0;
  8608. var wrappedV = ((v * height) % height) | 0;
  8609. // let wrappedU = (Math.abs(u) - Math.floor(Math.abs(u))) * width | 0;
  8610. // let wrappedV = (Math.abs(v) - Math.floor(Math.abs(v))) * height | 0;
  8611. var position = (wrappedU + wrappedV * width) * 4;
  8612. return pixels[position] / 255;
  8613. };
  8614. /**
  8615. * Interpolates between a and b via alpha
  8616. * @param a The lower value (returned when alpha = 0)
  8617. * @param b The upper value (returned when alpha = 1)
  8618. * @param alpha The interpolation-factor
  8619. * @return The mixed value
  8620. */
  8621. Tools.Mix = function (a, b, alpha) {
  8622. return a * (1 - alpha) + b * alpha;
  8623. };
  8624. Tools.Instantiate = function (className) {
  8625. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8626. return Tools.RegisteredExternalClasses[className];
  8627. }
  8628. var arr = className.split(".");
  8629. var fn = (window || this);
  8630. for (var i = 0, len = arr.length; i < len; i++) {
  8631. fn = fn[arr[i]];
  8632. }
  8633. if (typeof fn !== "function") {
  8634. return null;
  8635. }
  8636. return fn;
  8637. };
  8638. /**
  8639. * Provides a slice function that will work even on IE
  8640. * @param data defines the array to slice
  8641. * @param start defines the start of the data (optional)
  8642. * @param end defines the end of the data (optional)
  8643. * @returns the new sliced array
  8644. */
  8645. Tools.Slice = function (data, start, end) {
  8646. if (data.slice) {
  8647. return data.slice(start, end);
  8648. }
  8649. return Array.prototype.slice.call(data, start, end);
  8650. };
  8651. Tools.SetImmediate = function (action) {
  8652. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8653. window.setImmediate(action);
  8654. }
  8655. else {
  8656. setTimeout(action, 1);
  8657. }
  8658. };
  8659. Tools.IsExponentOfTwo = function (value) {
  8660. var count = 1;
  8661. do {
  8662. count *= 2;
  8663. } while (count < value);
  8664. return count === value;
  8665. };
  8666. /**
  8667. * Returns the nearest 32-bit single precision float representation of a Number
  8668. * @param value A Number. If the parameter is of a different type, it will get converted
  8669. * to a number or to NaN if it cannot be converted
  8670. * @returns number
  8671. */
  8672. Tools.FloatRound = function (value) {
  8673. if (Math.fround) {
  8674. return Math.fround(value);
  8675. }
  8676. return (Tools._tmpFloatArray[0] = value);
  8677. };
  8678. /**
  8679. * Find the next highest power of two.
  8680. * @param x Number to start search from.
  8681. * @return Next highest power of two.
  8682. */
  8683. Tools.CeilingPOT = function (x) {
  8684. x--;
  8685. x |= x >> 1;
  8686. x |= x >> 2;
  8687. x |= x >> 4;
  8688. x |= x >> 8;
  8689. x |= x >> 16;
  8690. x++;
  8691. return x;
  8692. };
  8693. /**
  8694. * Find the next lowest power of two.
  8695. * @param x Number to start search from.
  8696. * @return Next lowest power of two.
  8697. */
  8698. Tools.FloorPOT = function (x) {
  8699. x = x | (x >> 1);
  8700. x = x | (x >> 2);
  8701. x = x | (x >> 4);
  8702. x = x | (x >> 8);
  8703. x = x | (x >> 16);
  8704. return x - (x >> 1);
  8705. };
  8706. /**
  8707. * Find the nearest power of two.
  8708. * @param x Number to start search from.
  8709. * @return Next nearest power of two.
  8710. */
  8711. Tools.NearestPOT = function (x) {
  8712. var c = Tools.CeilingPOT(x);
  8713. var f = Tools.FloorPOT(x);
  8714. return (c - x) > (x - f) ? f : c;
  8715. };
  8716. Tools.GetExponentOfTwo = function (value, max, mode) {
  8717. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8718. var pot;
  8719. switch (mode) {
  8720. case BABYLON.Engine.SCALEMODE_FLOOR:
  8721. pot = Tools.FloorPOT(value);
  8722. break;
  8723. case BABYLON.Engine.SCALEMODE_NEAREST:
  8724. pot = Tools.NearestPOT(value);
  8725. break;
  8726. case BABYLON.Engine.SCALEMODE_CEILING:
  8727. default:
  8728. pot = Tools.CeilingPOT(value);
  8729. break;
  8730. }
  8731. return Math.min(pot, max);
  8732. };
  8733. Tools.GetFilename = function (path) {
  8734. var index = path.lastIndexOf("/");
  8735. if (index < 0)
  8736. return path;
  8737. return path.substring(index + 1);
  8738. };
  8739. /**
  8740. * Extracts the "folder" part of a path (everything before the filename).
  8741. * @param uri The URI to extract the info from
  8742. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8743. * @returns The "folder" part of the path
  8744. */
  8745. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8746. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8747. var index = uri.lastIndexOf("/");
  8748. if (index < 0) {
  8749. if (returnUnchangedIfNoSlash) {
  8750. return uri;
  8751. }
  8752. return "";
  8753. }
  8754. return uri.substring(0, index + 1);
  8755. };
  8756. Tools.GetDOMTextContent = function (element) {
  8757. var result = "";
  8758. var child = element.firstChild;
  8759. while (child) {
  8760. if (child.nodeType === 3) {
  8761. result += child.textContent;
  8762. }
  8763. child = child.nextSibling;
  8764. }
  8765. return result;
  8766. };
  8767. Tools.ToDegrees = function (angle) {
  8768. return angle * 180 / Math.PI;
  8769. };
  8770. Tools.ToRadians = function (angle) {
  8771. return angle * Math.PI / 180;
  8772. };
  8773. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8774. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8775. var output = "";
  8776. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8777. var i = 0;
  8778. var bytes = new Uint8Array(buffer);
  8779. while (i < bytes.length) {
  8780. chr1 = bytes[i++];
  8781. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8782. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8783. enc1 = chr1 >> 2;
  8784. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8785. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8786. enc4 = chr3 & 63;
  8787. if (isNaN(chr2)) {
  8788. enc3 = enc4 = 64;
  8789. }
  8790. else if (isNaN(chr3)) {
  8791. enc4 = 64;
  8792. }
  8793. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8794. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8795. }
  8796. return "data:image/png;base64," + output;
  8797. };
  8798. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8799. if (bias === void 0) { bias = null; }
  8800. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8801. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8802. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8803. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8804. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8805. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8806. }
  8807. if (bias) {
  8808. minimum.x -= minimum.x * bias.x + bias.y;
  8809. minimum.y -= minimum.y * bias.x + bias.y;
  8810. minimum.z -= minimum.z * bias.x + bias.y;
  8811. maximum.x += maximum.x * bias.x + bias.y;
  8812. maximum.y += maximum.y * bias.x + bias.y;
  8813. maximum.z += maximum.z * bias.x + bias.y;
  8814. }
  8815. return {
  8816. minimum: minimum,
  8817. maximum: maximum
  8818. };
  8819. };
  8820. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8821. if (bias === void 0) { bias = null; }
  8822. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8823. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8824. if (!stride) {
  8825. stride = 3;
  8826. }
  8827. for (var index = start; index < start + count; index++) {
  8828. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8829. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8830. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8831. }
  8832. if (bias) {
  8833. minimum.x -= minimum.x * bias.x + bias.y;
  8834. minimum.y -= minimum.y * bias.x + bias.y;
  8835. minimum.z -= minimum.z * bias.x + bias.y;
  8836. maximum.x += maximum.x * bias.x + bias.y;
  8837. maximum.y += maximum.y * bias.x + bias.y;
  8838. maximum.z += maximum.z * bias.x + bias.y;
  8839. }
  8840. return {
  8841. minimum: minimum,
  8842. maximum: maximum
  8843. };
  8844. };
  8845. Tools.Vector2ArrayFeeder = function (array) {
  8846. return function (index) {
  8847. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8848. var length = isFloatArray ? array.length / 2 : array.length;
  8849. if (index >= length) {
  8850. return null;
  8851. }
  8852. if (isFloatArray) {
  8853. var fa = array;
  8854. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8855. }
  8856. var a = array;
  8857. return a[index];
  8858. };
  8859. };
  8860. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8861. if (bias === void 0) { bias = null; }
  8862. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8863. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8864. var i = 0;
  8865. var cur = feeder(i++);
  8866. while (cur) {
  8867. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8868. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8869. cur = feeder(i++);
  8870. }
  8871. if (bias) {
  8872. minimum.x -= minimum.x * bias.x + bias.y;
  8873. minimum.y -= minimum.y * bias.x + bias.y;
  8874. maximum.x += maximum.x * bias.x + bias.y;
  8875. maximum.y += maximum.y * bias.x + bias.y;
  8876. }
  8877. return {
  8878. minimum: minimum,
  8879. maximum: maximum
  8880. };
  8881. };
  8882. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8883. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8884. return null;
  8885. return Array.isArray(obj) ? obj : [obj];
  8886. };
  8887. // Misc.
  8888. Tools.GetPointerPrefix = function () {
  8889. var eventPrefix = "pointer";
  8890. // Check if pointer events are supported
  8891. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8892. eventPrefix = "mouse";
  8893. }
  8894. return eventPrefix;
  8895. };
  8896. /**
  8897. * @param func - the function to be called
  8898. * @param requester - the object that will request the next frame. Falls back to window.
  8899. */
  8900. Tools.QueueNewFrame = function (func, requester) {
  8901. if (!Tools.IsWindowObjectExist()) {
  8902. return setTimeout(func, 16);
  8903. }
  8904. if (!requester) {
  8905. requester = window;
  8906. }
  8907. if (requester.requestAnimationFrame) {
  8908. return requester.requestAnimationFrame(func);
  8909. }
  8910. else if (requester.msRequestAnimationFrame) {
  8911. return requester.msRequestAnimationFrame(func);
  8912. }
  8913. else if (requester.webkitRequestAnimationFrame) {
  8914. return requester.webkitRequestAnimationFrame(func);
  8915. }
  8916. else if (requester.mozRequestAnimationFrame) {
  8917. return requester.mozRequestAnimationFrame(func);
  8918. }
  8919. else if (requester.oRequestAnimationFrame) {
  8920. return requester.oRequestAnimationFrame(func);
  8921. }
  8922. else {
  8923. return window.setTimeout(func, 16);
  8924. }
  8925. };
  8926. Tools.RequestFullscreen = function (element) {
  8927. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8928. if (!requestFunction)
  8929. return;
  8930. requestFunction.call(element);
  8931. };
  8932. Tools.ExitFullscreen = function () {
  8933. if (document.exitFullscreen) {
  8934. document.exitFullscreen();
  8935. }
  8936. else if (document.mozCancelFullScreen) {
  8937. document.mozCancelFullScreen();
  8938. }
  8939. else if (document.webkitCancelFullScreen) {
  8940. document.webkitCancelFullScreen();
  8941. }
  8942. else if (document.msCancelFullScreen) {
  8943. document.msCancelFullScreen();
  8944. }
  8945. };
  8946. Tools.SetCorsBehavior = function (url, element) {
  8947. if (url && url.indexOf("data:") === 0) {
  8948. return;
  8949. }
  8950. if (Tools.CorsBehavior) {
  8951. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8952. element.crossOrigin = Tools.CorsBehavior;
  8953. }
  8954. else {
  8955. var result = Tools.CorsBehavior(url);
  8956. if (result) {
  8957. element.crossOrigin = result;
  8958. }
  8959. }
  8960. }
  8961. };
  8962. // External files
  8963. Tools.CleanUrl = function (url) {
  8964. url = url.replace(/#/mg, "%23");
  8965. return url;
  8966. };
  8967. /**
  8968. * Loads an image as an HTMLImageElement.
  8969. * @param input url string, ArrayBuffer, or Blob to load
  8970. * @param onLoad callback called when the image successfully loads
  8971. * @param onError callback called when the image fails to load
  8972. * @param database database for caching
  8973. * @returns the HTMLImageElement of the loaded image
  8974. */
  8975. Tools.LoadImage = function (input, onLoad, onError, database) {
  8976. var url;
  8977. var usingObjectURL = false;
  8978. if (input instanceof ArrayBuffer) {
  8979. url = URL.createObjectURL(new Blob([input]));
  8980. usingObjectURL = true;
  8981. }
  8982. else if (input instanceof Blob) {
  8983. url = URL.createObjectURL(input);
  8984. usingObjectURL = true;
  8985. }
  8986. else {
  8987. url = Tools.CleanUrl(input);
  8988. url = Tools.PreprocessUrl(input);
  8989. }
  8990. var img = new Image();
  8991. Tools.SetCorsBehavior(url, img);
  8992. var loadHandler = function () {
  8993. if (usingObjectURL && img.src) {
  8994. URL.revokeObjectURL(img.src);
  8995. }
  8996. img.removeEventListener("load", loadHandler);
  8997. img.removeEventListener("error", errorHandler);
  8998. onLoad(img);
  8999. };
  9000. var errorHandler = function (err) {
  9001. if (usingObjectURL && img.src) {
  9002. URL.revokeObjectURL(img.src);
  9003. }
  9004. img.removeEventListener("load", loadHandler);
  9005. img.removeEventListener("error", errorHandler);
  9006. Tools.Error("Error while trying to load image: " + input);
  9007. if (onError) {
  9008. onError("Error while trying to load image: " + input, err);
  9009. }
  9010. };
  9011. img.addEventListener("load", loadHandler);
  9012. img.addEventListener("error", errorHandler);
  9013. var noIndexedDB = function () {
  9014. img.src = url;
  9015. };
  9016. var loadFromIndexedDB = function () {
  9017. if (database) {
  9018. database.loadImageFromDB(url, img);
  9019. }
  9020. };
  9021. //ANY database to do!
  9022. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9023. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9024. }
  9025. else {
  9026. if (url.indexOf("file:") !== -1) {
  9027. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9028. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9029. try {
  9030. var blobURL;
  9031. try {
  9032. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9033. }
  9034. catch (ex) {
  9035. // Chrome doesn't support oneTimeOnly parameter
  9036. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9037. }
  9038. img.src = blobURL;
  9039. usingObjectURL = true;
  9040. }
  9041. catch (e) {
  9042. img.src = "";
  9043. }
  9044. return img;
  9045. }
  9046. }
  9047. noIndexedDB();
  9048. }
  9049. return img;
  9050. };
  9051. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9052. url = Tools.CleanUrl(url);
  9053. url = Tools.PreprocessUrl(url);
  9054. // If file and file input are set
  9055. if (url.indexOf("file:") !== -1) {
  9056. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9057. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9058. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9059. }
  9060. }
  9061. var loadUrl = Tools.BaseUrl + url;
  9062. var aborted = false;
  9063. var fileRequest = {
  9064. onCompleteObservable: new BABYLON.Observable(),
  9065. abort: function () { return aborted = true; },
  9066. };
  9067. var requestFile = function () {
  9068. var request = new XMLHttpRequest();
  9069. var retryHandle = null;
  9070. fileRequest.abort = function () {
  9071. aborted = true;
  9072. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9073. request.abort();
  9074. }
  9075. if (retryHandle !== null) {
  9076. clearTimeout(retryHandle);
  9077. retryHandle = null;
  9078. }
  9079. };
  9080. var retryLoop = function (retryIndex) {
  9081. request.open('GET', loadUrl, true);
  9082. if (useArrayBuffer) {
  9083. request.responseType = "arraybuffer";
  9084. }
  9085. if (onProgress) {
  9086. request.addEventListener("progress", onProgress);
  9087. }
  9088. var onLoadEnd = function () {
  9089. request.removeEventListener("loadend", onLoadEnd);
  9090. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9091. fileRequest.onCompleteObservable.clear();
  9092. };
  9093. request.addEventListener("loadend", onLoadEnd);
  9094. var onReadyStateChange = function () {
  9095. if (aborted) {
  9096. return;
  9097. }
  9098. // In case of undefined state in some browsers.
  9099. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9100. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9101. request.removeEventListener("readystatechange", onReadyStateChange);
  9102. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9103. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9104. return;
  9105. }
  9106. var retryStrategy = Tools.DefaultRetryStrategy;
  9107. if (retryStrategy) {
  9108. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9109. if (waitTime !== -1) {
  9110. // Prevent the request from completing for retry.
  9111. request.removeEventListener("loadend", onLoadEnd);
  9112. request = new XMLHttpRequest();
  9113. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9114. return;
  9115. }
  9116. }
  9117. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9118. if (onError) {
  9119. onError(request, e);
  9120. }
  9121. else {
  9122. throw e;
  9123. }
  9124. }
  9125. };
  9126. request.addEventListener("readystatechange", onReadyStateChange);
  9127. request.send();
  9128. };
  9129. retryLoop(0);
  9130. };
  9131. // Caching all files
  9132. if (database && database.enableSceneOffline) {
  9133. var noIndexedDB_1 = function (request) {
  9134. if (request && request.status > 400) {
  9135. if (onError) {
  9136. onError(request);
  9137. }
  9138. }
  9139. else {
  9140. if (!aborted) {
  9141. requestFile();
  9142. }
  9143. }
  9144. };
  9145. var loadFromIndexedDB = function () {
  9146. // TODO: database needs to support aborting and should return a IFileRequest
  9147. if (aborted) {
  9148. return;
  9149. }
  9150. if (database) {
  9151. database.loadFileFromDB(url, function (data) {
  9152. if (!aborted) {
  9153. onSuccess(data);
  9154. }
  9155. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9156. }, onProgress ? function (event) {
  9157. if (!aborted) {
  9158. onProgress(event);
  9159. }
  9160. } : undefined, noIndexedDB_1, useArrayBuffer);
  9161. }
  9162. };
  9163. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9164. }
  9165. else {
  9166. requestFile();
  9167. }
  9168. return fileRequest;
  9169. };
  9170. /**
  9171. * Load a script (identified by an url). When the url returns, the
  9172. * content of this file is added into a new script element, attached to the DOM (body element)
  9173. */
  9174. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9175. var head = document.getElementsByTagName('head')[0];
  9176. var script = document.createElement('script');
  9177. script.type = 'text/javascript';
  9178. script.src = scriptUrl;
  9179. script.onload = function () {
  9180. if (onSuccess) {
  9181. onSuccess();
  9182. }
  9183. };
  9184. script.onerror = function (e) {
  9185. if (onError) {
  9186. onError("Unable to load script '" + scriptUrl + "'", e);
  9187. }
  9188. };
  9189. head.appendChild(script);
  9190. };
  9191. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9192. var reader = new FileReader();
  9193. var request = {
  9194. onCompleteObservable: new BABYLON.Observable(),
  9195. abort: function () { return reader.abort(); },
  9196. };
  9197. reader.onloadend = function (e) {
  9198. request.onCompleteObservable.notifyObservers(request);
  9199. };
  9200. reader.onload = function (e) {
  9201. //target doesn't have result from ts 1.3
  9202. callback(e.target['result']);
  9203. };
  9204. reader.onprogress = progressCallback;
  9205. reader.readAsDataURL(fileToLoad);
  9206. return request;
  9207. };
  9208. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9209. var reader = new FileReader();
  9210. var request = {
  9211. onCompleteObservable: new BABYLON.Observable(),
  9212. abort: function () { return reader.abort(); },
  9213. };
  9214. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9215. reader.onerror = function (e) {
  9216. Tools.Log("Error while reading file: " + fileToLoad.name);
  9217. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9218. };
  9219. reader.onload = function (e) {
  9220. //target doesn't have result from ts 1.3
  9221. callback(e.target['result']);
  9222. };
  9223. if (progressCallBack) {
  9224. reader.onprogress = progressCallBack;
  9225. }
  9226. if (!useArrayBuffer) {
  9227. // Asynchronous read
  9228. reader.readAsText(fileToLoad);
  9229. }
  9230. else {
  9231. reader.readAsArrayBuffer(fileToLoad);
  9232. }
  9233. return request;
  9234. };
  9235. //returns a downloadable url to a file content.
  9236. Tools.FileAsURL = function (content) {
  9237. var fileBlob = new Blob([content]);
  9238. var url = window.URL || window.webkitURL;
  9239. var link = url.createObjectURL(fileBlob);
  9240. return link;
  9241. };
  9242. // Misc.
  9243. Tools.Format = function (value, decimals) {
  9244. if (decimals === void 0) { decimals = 2; }
  9245. return value.toFixed(decimals);
  9246. };
  9247. Tools.CheckExtends = function (v, min, max) {
  9248. if (v.x < min.x)
  9249. min.x = v.x;
  9250. if (v.y < min.y)
  9251. min.y = v.y;
  9252. if (v.z < min.z)
  9253. min.z = v.z;
  9254. if (v.x > max.x)
  9255. max.x = v.x;
  9256. if (v.y > max.y)
  9257. max.y = v.y;
  9258. if (v.z > max.z)
  9259. max.z = v.z;
  9260. };
  9261. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9262. for (var prop in source) {
  9263. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9264. continue;
  9265. }
  9266. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9267. continue;
  9268. }
  9269. var sourceValue = source[prop];
  9270. var typeOfSourceValue = typeof sourceValue;
  9271. if (typeOfSourceValue === "function") {
  9272. continue;
  9273. }
  9274. try {
  9275. if (typeOfSourceValue === "object") {
  9276. if (sourceValue instanceof Array) {
  9277. destination[prop] = [];
  9278. if (sourceValue.length > 0) {
  9279. if (typeof sourceValue[0] == "object") {
  9280. for (var index = 0; index < sourceValue.length; index++) {
  9281. var clonedValue = cloneValue(sourceValue[index], destination);
  9282. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9283. destination[prop].push(clonedValue);
  9284. }
  9285. }
  9286. }
  9287. else {
  9288. destination[prop] = sourceValue.slice(0);
  9289. }
  9290. }
  9291. }
  9292. else {
  9293. destination[prop] = cloneValue(sourceValue, destination);
  9294. }
  9295. }
  9296. else {
  9297. destination[prop] = sourceValue;
  9298. }
  9299. }
  9300. catch (e) {
  9301. // Just ignore error (it could be because of a read-only property)
  9302. }
  9303. }
  9304. };
  9305. Tools.IsEmpty = function (obj) {
  9306. for (var i in obj) {
  9307. if (obj.hasOwnProperty(i)) {
  9308. return false;
  9309. }
  9310. }
  9311. return true;
  9312. };
  9313. Tools.RegisterTopRootEvents = function (events) {
  9314. for (var index = 0; index < events.length; index++) {
  9315. var event = events[index];
  9316. window.addEventListener(event.name, event.handler, false);
  9317. try {
  9318. if (window.parent) {
  9319. window.parent.addEventListener(event.name, event.handler, false);
  9320. }
  9321. }
  9322. catch (e) {
  9323. // Silently fails...
  9324. }
  9325. }
  9326. };
  9327. Tools.UnregisterTopRootEvents = function (events) {
  9328. for (var index = 0; index < events.length; index++) {
  9329. var event = events[index];
  9330. window.removeEventListener(event.name, event.handler);
  9331. try {
  9332. if (window.parent) {
  9333. window.parent.removeEventListener(event.name, event.handler);
  9334. }
  9335. }
  9336. catch (e) {
  9337. // Silently fails...
  9338. }
  9339. }
  9340. };
  9341. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9342. if (mimeType === void 0) { mimeType = "image/png"; }
  9343. // Read the contents of the framebuffer
  9344. var numberOfChannelsByLine = width * 4;
  9345. var halfHeight = height / 2;
  9346. //Reading datas from WebGL
  9347. var data = engine.readPixels(0, 0, width, height);
  9348. //To flip image on Y axis.
  9349. for (var i = 0; i < halfHeight; i++) {
  9350. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9351. var currentCell = j + i * numberOfChannelsByLine;
  9352. var targetLine = height - i - 1;
  9353. var targetCell = j + targetLine * numberOfChannelsByLine;
  9354. var temp = data[currentCell];
  9355. data[currentCell] = data[targetCell];
  9356. data[targetCell] = temp;
  9357. }
  9358. }
  9359. // Create a 2D canvas to store the result
  9360. if (!screenshotCanvas) {
  9361. screenshotCanvas = document.createElement('canvas');
  9362. }
  9363. screenshotCanvas.width = width;
  9364. screenshotCanvas.height = height;
  9365. var context = screenshotCanvas.getContext('2d');
  9366. if (context) {
  9367. // Copy the pixels to a 2D canvas
  9368. var imageData = context.createImageData(width, height);
  9369. var castData = (imageData.data);
  9370. castData.set(data);
  9371. context.putImageData(imageData, 0, 0);
  9372. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9373. }
  9374. };
  9375. /**
  9376. * Converts the canvas data to blob.
  9377. * This acts as a polyfill for browsers not supporting the to blob function.
  9378. * @param canvas Defines the canvas to extract the data from
  9379. * @param successCallback Defines the callback triggered once the data are available
  9380. * @param mimeType Defines the mime type of the result
  9381. */
  9382. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9383. if (mimeType === void 0) { mimeType = "image/png"; }
  9384. // We need HTMLCanvasElement.toBlob for HD screenshots
  9385. if (!canvas.toBlob) {
  9386. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9387. canvas.toBlob = function (callback, type, quality) {
  9388. var _this = this;
  9389. setTimeout(function () {
  9390. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9391. for (var i = 0; i < len; i++) {
  9392. arr[i] = binStr.charCodeAt(i);
  9393. }
  9394. callback(new Blob([arr]));
  9395. });
  9396. };
  9397. }
  9398. canvas.toBlob(function (blob) {
  9399. successCallback(blob);
  9400. }, mimeType);
  9401. };
  9402. /**
  9403. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9404. * @param successCallback Defines the callback triggered once the data are available
  9405. * @param mimeType Defines the mime type of the result
  9406. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9407. */
  9408. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9409. if (mimeType === void 0) { mimeType = "image/png"; }
  9410. if (successCallback) {
  9411. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9412. successCallback(base64Image);
  9413. }
  9414. else {
  9415. this.ToBlob(screenshotCanvas, function (blob) {
  9416. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9417. if (("download" in document.createElement("a"))) {
  9418. if (!fileName) {
  9419. var date = new Date();
  9420. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9421. fileName = "screenshot_" + stringDate + ".png";
  9422. }
  9423. Tools.Download(blob, fileName);
  9424. }
  9425. else {
  9426. var url = URL.createObjectURL(blob);
  9427. var newWindow = window.open("");
  9428. if (!newWindow)
  9429. return;
  9430. var img = newWindow.document.createElement("img");
  9431. img.onload = function () {
  9432. // no longer need to read the blob so it's revoked
  9433. URL.revokeObjectURL(url);
  9434. };
  9435. img.src = url;
  9436. newWindow.document.body.appendChild(img);
  9437. }
  9438. }, mimeType);
  9439. }
  9440. };
  9441. /**
  9442. * Downloads a blob in the browser
  9443. * @param blob defines the blob to download
  9444. * @param fileName defines the name of the downloaded file
  9445. */
  9446. Tools.Download = function (blob, fileName) {
  9447. if (navigator && navigator.msSaveBlob) {
  9448. navigator.msSaveBlob(blob, fileName);
  9449. return;
  9450. }
  9451. var url = window.URL.createObjectURL(blob);
  9452. var a = document.createElement("a");
  9453. document.body.appendChild(a);
  9454. a.style.display = "none";
  9455. a.href = url;
  9456. a.download = fileName;
  9457. a.addEventListener("click", function () {
  9458. if (a.parentElement) {
  9459. a.parentElement.removeChild(a);
  9460. }
  9461. });
  9462. a.click();
  9463. window.URL.revokeObjectURL(url);
  9464. };
  9465. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9466. if (mimeType === void 0) { mimeType = "image/png"; }
  9467. var width;
  9468. var height;
  9469. // If a precision value is specified
  9470. if (size.precision) {
  9471. width = Math.round(engine.getRenderWidth() * size.precision);
  9472. height = Math.round(width / engine.getAspectRatio(camera));
  9473. }
  9474. else if (size.width && size.height) {
  9475. width = size.width;
  9476. height = size.height;
  9477. }
  9478. //If passing only width, computing height to keep display canvas ratio.
  9479. else if (size.width && !size.height) {
  9480. width = size.width;
  9481. height = Math.round(width / engine.getAspectRatio(camera));
  9482. }
  9483. //If passing only height, computing width to keep display canvas ratio.
  9484. else if (size.height && !size.width) {
  9485. height = size.height;
  9486. width = Math.round(height * engine.getAspectRatio(camera));
  9487. }
  9488. //Assuming here that "size" parameter is a number
  9489. else if (!isNaN(size)) {
  9490. height = size;
  9491. width = size;
  9492. }
  9493. else {
  9494. Tools.Error("Invalid 'size' parameter !");
  9495. return;
  9496. }
  9497. if (!screenshotCanvas) {
  9498. screenshotCanvas = document.createElement('canvas');
  9499. }
  9500. screenshotCanvas.width = width;
  9501. screenshotCanvas.height = height;
  9502. var renderContext = screenshotCanvas.getContext("2d");
  9503. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9504. var newWidth = width;
  9505. var newHeight = newWidth / ratio;
  9506. if (newHeight > height) {
  9507. newHeight = height;
  9508. newWidth = newHeight * ratio;
  9509. }
  9510. var offsetX = Math.max(0, width - newWidth) / 2;
  9511. var offsetY = Math.max(0, height - newHeight) / 2;
  9512. var renderingCanvas = engine.getRenderingCanvas();
  9513. if (renderContext && renderingCanvas) {
  9514. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9515. }
  9516. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9517. };
  9518. /**
  9519. * Generates an image screenshot from the specified camera.
  9520. *
  9521. * @param engine The engine to use for rendering
  9522. * @param camera The camera to use for rendering
  9523. * @param size This parameter can be set to a single number or to an object with the
  9524. * following (optional) properties: precision, width, height. If a single number is passed,
  9525. * it will be used for both width and height. If an object is passed, the screenshot size
  9526. * will be derived from the parameters. The precision property is a multiplier allowing
  9527. * rendering at a higher or lower resolution.
  9528. * @param successCallback The callback receives a single parameter which contains the
  9529. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9530. * src parameter of an <img> to display it.
  9531. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9532. * Check your browser for supported MIME types.
  9533. * @param samples Texture samples (default: 1)
  9534. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9535. * @param fileName A name for for the downloaded file.
  9536. * @constructor
  9537. */
  9538. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9539. if (mimeType === void 0) { mimeType = "image/png"; }
  9540. if (samples === void 0) { samples = 1; }
  9541. if (antialiasing === void 0) { antialiasing = false; }
  9542. var width;
  9543. var height;
  9544. //If a precision value is specified
  9545. if (size.precision) {
  9546. width = Math.round(engine.getRenderWidth() * size.precision);
  9547. height = Math.round(width / engine.getAspectRatio(camera));
  9548. size = { width: width, height: height };
  9549. }
  9550. else if (size.width && size.height) {
  9551. width = size.width;
  9552. height = size.height;
  9553. }
  9554. //If passing only width, computing height to keep display canvas ratio.
  9555. else if (size.width && !size.height) {
  9556. width = size.width;
  9557. height = Math.round(width / engine.getAspectRatio(camera));
  9558. size = { width: width, height: height };
  9559. }
  9560. //If passing only height, computing width to keep display canvas ratio.
  9561. else if (size.height && !size.width) {
  9562. height = size.height;
  9563. width = Math.round(height * engine.getAspectRatio(camera));
  9564. size = { width: width, height: height };
  9565. }
  9566. //Assuming here that "size" parameter is a number
  9567. else if (!isNaN(size)) {
  9568. height = size;
  9569. width = size;
  9570. }
  9571. else {
  9572. Tools.Error("Invalid 'size' parameter !");
  9573. return;
  9574. }
  9575. var scene = camera.getScene();
  9576. var previousCamera = null;
  9577. if (scene.activeCamera !== camera) {
  9578. previousCamera = scene.activeCamera;
  9579. scene.activeCamera = camera;
  9580. }
  9581. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9582. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9583. texture.renderList = null;
  9584. texture.samples = samples;
  9585. if (antialiasing) {
  9586. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9587. }
  9588. texture.onAfterRenderObservable.add(function () {
  9589. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9590. });
  9591. scene.incrementRenderId();
  9592. scene.resetCachedMaterial();
  9593. texture.render(true);
  9594. texture.dispose();
  9595. if (previousCamera) {
  9596. scene.activeCamera = previousCamera;
  9597. }
  9598. camera.getProjectionMatrix(true); // Force cache refresh;
  9599. };
  9600. // XHR response validator for local file scenario
  9601. Tools.ValidateXHRData = function (xhr, dataType) {
  9602. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9603. if (dataType === void 0) { dataType = 7; }
  9604. try {
  9605. if (dataType & 1) {
  9606. if (xhr.responseText && xhr.responseText.length > 0) {
  9607. return true;
  9608. }
  9609. else if (dataType === 1) {
  9610. return false;
  9611. }
  9612. }
  9613. if (dataType & 2) {
  9614. // Check header width and height since there is no "TGA" magic number
  9615. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9616. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9617. return true;
  9618. }
  9619. else if (dataType === 2) {
  9620. return false;
  9621. }
  9622. }
  9623. if (dataType & 4) {
  9624. // Check for the "DDS" magic number
  9625. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9626. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9627. return true;
  9628. }
  9629. else {
  9630. return false;
  9631. }
  9632. }
  9633. }
  9634. catch (e) {
  9635. // Global protection
  9636. }
  9637. return false;
  9638. };
  9639. /**
  9640. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9641. * Be aware Math.random() could cause collisions, but:
  9642. * "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"
  9643. */
  9644. Tools.RandomId = function () {
  9645. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9646. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9647. return v.toString(16);
  9648. });
  9649. };
  9650. /**
  9651. * Test if the given uri is a base64 string.
  9652. * @param uri The uri to test
  9653. * @return True if the uri is a base64 string or false otherwise.
  9654. */
  9655. Tools.IsBase64 = function (uri) {
  9656. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9657. };
  9658. /**
  9659. * Decode the given base64 uri.
  9660. * @param uri The uri to decode
  9661. * @return The decoded base64 data.
  9662. */
  9663. Tools.DecodeBase64 = function (uri) {
  9664. var decodedString = atob(uri.split(",")[1]);
  9665. var bufferLength = decodedString.length;
  9666. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9667. for (var i = 0; i < bufferLength; i++) {
  9668. bufferView[i] = decodedString.charCodeAt(i);
  9669. }
  9670. return bufferView.buffer;
  9671. };
  9672. Object.defineProperty(Tools, "NoneLogLevel", {
  9673. get: function () {
  9674. return Tools._NoneLogLevel;
  9675. },
  9676. enumerable: true,
  9677. configurable: true
  9678. });
  9679. Object.defineProperty(Tools, "MessageLogLevel", {
  9680. get: function () {
  9681. return Tools._MessageLogLevel;
  9682. },
  9683. enumerable: true,
  9684. configurable: true
  9685. });
  9686. Object.defineProperty(Tools, "WarningLogLevel", {
  9687. get: function () {
  9688. return Tools._WarningLogLevel;
  9689. },
  9690. enumerable: true,
  9691. configurable: true
  9692. });
  9693. Object.defineProperty(Tools, "ErrorLogLevel", {
  9694. get: function () {
  9695. return Tools._ErrorLogLevel;
  9696. },
  9697. enumerable: true,
  9698. configurable: true
  9699. });
  9700. Object.defineProperty(Tools, "AllLogLevel", {
  9701. get: function () {
  9702. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9703. },
  9704. enumerable: true,
  9705. configurable: true
  9706. });
  9707. Tools._AddLogEntry = function (entry) {
  9708. Tools._LogCache = entry + Tools._LogCache;
  9709. if (Tools.OnNewCacheEntry) {
  9710. Tools.OnNewCacheEntry(entry);
  9711. }
  9712. };
  9713. Tools._FormatMessage = function (message) {
  9714. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9715. var date = new Date();
  9716. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9717. };
  9718. Tools._LogDisabled = function (message) {
  9719. // nothing to do
  9720. };
  9721. Tools._LogEnabled = function (message) {
  9722. var formattedMessage = Tools._FormatMessage(message);
  9723. console.log("BJS - " + formattedMessage);
  9724. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9725. Tools._AddLogEntry(entry);
  9726. };
  9727. Tools._WarnDisabled = function (message) {
  9728. // nothing to do
  9729. };
  9730. Tools._WarnEnabled = function (message) {
  9731. var formattedMessage = Tools._FormatMessage(message);
  9732. console.warn("BJS - " + formattedMessage);
  9733. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9734. Tools._AddLogEntry(entry);
  9735. };
  9736. Tools._ErrorDisabled = function (message) {
  9737. // nothing to do
  9738. };
  9739. Tools._ErrorEnabled = function (message) {
  9740. Tools.errorsCount++;
  9741. var formattedMessage = Tools._FormatMessage(message);
  9742. console.error("BJS - " + formattedMessage);
  9743. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9744. Tools._AddLogEntry(entry);
  9745. };
  9746. Object.defineProperty(Tools, "LogCache", {
  9747. get: function () {
  9748. return Tools._LogCache;
  9749. },
  9750. enumerable: true,
  9751. configurable: true
  9752. });
  9753. Tools.ClearLogCache = function () {
  9754. Tools._LogCache = "";
  9755. Tools.errorsCount = 0;
  9756. };
  9757. Object.defineProperty(Tools, "LogLevels", {
  9758. set: function (level) {
  9759. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9760. Tools.Log = Tools._LogEnabled;
  9761. }
  9762. else {
  9763. Tools.Log = Tools._LogDisabled;
  9764. }
  9765. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9766. Tools.Warn = Tools._WarnEnabled;
  9767. }
  9768. else {
  9769. Tools.Warn = Tools._WarnDisabled;
  9770. }
  9771. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9772. Tools.Error = Tools._ErrorEnabled;
  9773. }
  9774. else {
  9775. Tools.Error = Tools._ErrorDisabled;
  9776. }
  9777. },
  9778. enumerable: true,
  9779. configurable: true
  9780. });
  9781. Tools.IsWindowObjectExist = function () {
  9782. return (typeof window) !== "undefined";
  9783. };
  9784. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9785. get: function () {
  9786. return Tools._PerformanceNoneLogLevel;
  9787. },
  9788. enumerable: true,
  9789. configurable: true
  9790. });
  9791. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9792. get: function () {
  9793. return Tools._PerformanceUserMarkLogLevel;
  9794. },
  9795. enumerable: true,
  9796. configurable: true
  9797. });
  9798. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9799. get: function () {
  9800. return Tools._PerformanceConsoleLogLevel;
  9801. },
  9802. enumerable: true,
  9803. configurable: true
  9804. });
  9805. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9806. set: function (level) {
  9807. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9808. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9809. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9810. return;
  9811. }
  9812. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9813. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9814. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9815. return;
  9816. }
  9817. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9818. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9819. },
  9820. enumerable: true,
  9821. configurable: true
  9822. });
  9823. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9824. };
  9825. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9826. };
  9827. Tools._StartUserMark = function (counterName, condition) {
  9828. if (condition === void 0) { condition = true; }
  9829. if (!Tools._performance) {
  9830. if (!Tools.IsWindowObjectExist()) {
  9831. return;
  9832. }
  9833. Tools._performance = window.performance;
  9834. }
  9835. if (!condition || !Tools._performance.mark) {
  9836. return;
  9837. }
  9838. Tools._performance.mark(counterName + "-Begin");
  9839. };
  9840. Tools._EndUserMark = function (counterName, condition) {
  9841. if (condition === void 0) { condition = true; }
  9842. if (!condition || !Tools._performance.mark) {
  9843. return;
  9844. }
  9845. Tools._performance.mark(counterName + "-End");
  9846. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9847. };
  9848. Tools._StartPerformanceConsole = function (counterName, condition) {
  9849. if (condition === void 0) { condition = true; }
  9850. if (!condition) {
  9851. return;
  9852. }
  9853. Tools._StartUserMark(counterName, condition);
  9854. if (console.time) {
  9855. console.time(counterName);
  9856. }
  9857. };
  9858. Tools._EndPerformanceConsole = function (counterName, condition) {
  9859. if (condition === void 0) { condition = true; }
  9860. if (!condition) {
  9861. return;
  9862. }
  9863. Tools._EndUserMark(counterName, condition);
  9864. if (console.time) {
  9865. console.timeEnd(counterName);
  9866. }
  9867. };
  9868. Object.defineProperty(Tools, "Now", {
  9869. get: function () {
  9870. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9871. return window.performance.now();
  9872. }
  9873. return Date.now();
  9874. },
  9875. enumerable: true,
  9876. configurable: true
  9877. });
  9878. /**
  9879. * This method will return the name of the class used to create the instance of the given object.
  9880. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9881. * @param object the object to get the class name from
  9882. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9883. */
  9884. Tools.GetClassName = function (object, isType) {
  9885. if (isType === void 0) { isType = false; }
  9886. var name = null;
  9887. if (!isType && object.getClassName) {
  9888. name = object.getClassName();
  9889. }
  9890. else {
  9891. if (object instanceof Object) {
  9892. var classObj = isType ? object : Object.getPrototypeOf(object);
  9893. name = classObj.constructor["__bjsclassName__"];
  9894. }
  9895. if (!name) {
  9896. name = typeof object;
  9897. }
  9898. }
  9899. return name;
  9900. };
  9901. Tools.First = function (array, predicate) {
  9902. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9903. var el = array_1[_i];
  9904. if (predicate(el)) {
  9905. return el;
  9906. }
  9907. }
  9908. return null;
  9909. };
  9910. /**
  9911. * This method will return the name of the full name of the class, including its owning module (if any).
  9912. * 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).
  9913. * @param object the object to get the class name from
  9914. * @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.
  9915. */
  9916. Tools.getFullClassName = function (object, isType) {
  9917. if (isType === void 0) { isType = false; }
  9918. var className = null;
  9919. var moduleName = null;
  9920. if (!isType && object.getClassName) {
  9921. className = object.getClassName();
  9922. }
  9923. else {
  9924. if (object instanceof Object) {
  9925. var classObj = isType ? object : Object.getPrototypeOf(object);
  9926. className = classObj.constructor["__bjsclassName__"];
  9927. moduleName = classObj.constructor["__bjsmoduleName__"];
  9928. }
  9929. if (!className) {
  9930. className = typeof object;
  9931. }
  9932. }
  9933. if (!className) {
  9934. return null;
  9935. }
  9936. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9937. };
  9938. /**
  9939. * 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.
  9940. * @param array
  9941. */
  9942. Tools.arrayOrStringFeeder = function (array) {
  9943. return function (index) {
  9944. if (index >= array.length) {
  9945. return null;
  9946. }
  9947. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9948. if (val && val.getHashCode) {
  9949. val = val.getHashCode();
  9950. }
  9951. if (typeof val === "string") {
  9952. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9953. }
  9954. return val;
  9955. };
  9956. };
  9957. /**
  9958. * Compute the hashCode of a stream of number
  9959. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9960. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9961. * @return the hash code computed
  9962. */
  9963. Tools.hashCodeFromStream = function (feeder) {
  9964. // Based from here: http://stackoverflow.com/a/7616484/802124
  9965. var hash = 0;
  9966. var index = 0;
  9967. var chr = feeder(index++);
  9968. while (chr != null) {
  9969. hash = ((hash << 5) - hash) + chr;
  9970. hash |= 0; // Convert to 32bit integer
  9971. chr = feeder(index++);
  9972. }
  9973. return hash;
  9974. };
  9975. /**
  9976. * Returns a promise that resolves after the given amount of time.
  9977. * @param delay Number of milliseconds to delay
  9978. * @returns Promise that resolves after the given amount of time
  9979. */
  9980. Tools.DelayAsync = function (delay) {
  9981. return new Promise(function (resolve) {
  9982. setTimeout(function () {
  9983. resolve();
  9984. }, delay);
  9985. });
  9986. };
  9987. /**
  9988. * Gets the current gradient from an array of IValueGradient
  9989. * @param ratio defines the current ratio to get
  9990. * @param gradients defines the array of IValueGradient
  9991. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9992. */
  9993. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9994. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9995. var currentGradient = gradients[gradientIndex];
  9996. var nextGradient = gradients[gradientIndex + 1];
  9997. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9998. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9999. updateFunc(currentGradient, nextGradient, scale);
  10000. }
  10001. }
  10002. };
  10003. Tools.BaseUrl = "";
  10004. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10005. /**
  10006. * Default behaviour for cors in the application.
  10007. * It can be a string if the expected behavior is identical in the entire app.
  10008. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10009. */
  10010. Tools.CorsBehavior = "anonymous";
  10011. Tools.UseFallbackTexture = true;
  10012. /**
  10013. * Use this object to register external classes like custom textures or material
  10014. * to allow the laoders to instantiate them
  10015. */
  10016. Tools.RegisteredExternalClasses = {};
  10017. // Used in case of a texture loading problem
  10018. 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";
  10019. Tools._tmpFloatArray = new Float32Array(1);
  10020. Tools.PreprocessUrl = function (url) {
  10021. return url;
  10022. };
  10023. // Logs
  10024. Tools._NoneLogLevel = 0;
  10025. Tools._MessageLogLevel = 1;
  10026. Tools._WarningLogLevel = 2;
  10027. Tools._ErrorLogLevel = 4;
  10028. Tools._LogCache = "";
  10029. Tools.errorsCount = 0;
  10030. Tools.Log = Tools._LogEnabled;
  10031. Tools.Warn = Tools._WarnEnabled;
  10032. Tools.Error = Tools._ErrorEnabled;
  10033. // Performances
  10034. Tools._PerformanceNoneLogLevel = 0;
  10035. Tools._PerformanceUserMarkLogLevel = 1;
  10036. Tools._PerformanceConsoleLogLevel = 2;
  10037. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10038. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10039. return Tools;
  10040. }());
  10041. BABYLON.Tools = Tools;
  10042. /**
  10043. * This class is used to track a performance counter which is number based.
  10044. * The user has access to many properties which give statistics of different nature
  10045. *
  10046. * The implementer can track two kinds of Performance Counter: time and count
  10047. * 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.
  10048. * 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.
  10049. */
  10050. var PerfCounter = /** @class */ (function () {
  10051. function PerfCounter() {
  10052. this._startMonitoringTime = 0;
  10053. this._min = 0;
  10054. this._max = 0;
  10055. this._average = 0;
  10056. this._lastSecAverage = 0;
  10057. this._current = 0;
  10058. this._totalValueCount = 0;
  10059. this._totalAccumulated = 0;
  10060. this._lastSecAccumulated = 0;
  10061. this._lastSecTime = 0;
  10062. this._lastSecValueCount = 0;
  10063. }
  10064. Object.defineProperty(PerfCounter.prototype, "min", {
  10065. /**
  10066. * Returns the smallest value ever
  10067. */
  10068. get: function () {
  10069. return this._min;
  10070. },
  10071. enumerable: true,
  10072. configurable: true
  10073. });
  10074. Object.defineProperty(PerfCounter.prototype, "max", {
  10075. /**
  10076. * Returns the biggest value ever
  10077. */
  10078. get: function () {
  10079. return this._max;
  10080. },
  10081. enumerable: true,
  10082. configurable: true
  10083. });
  10084. Object.defineProperty(PerfCounter.prototype, "average", {
  10085. /**
  10086. * Returns the average value since the performance counter is running
  10087. */
  10088. get: function () {
  10089. return this._average;
  10090. },
  10091. enumerable: true,
  10092. configurable: true
  10093. });
  10094. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10095. /**
  10096. * Returns the average value of the last second the counter was monitored
  10097. */
  10098. get: function () {
  10099. return this._lastSecAverage;
  10100. },
  10101. enumerable: true,
  10102. configurable: true
  10103. });
  10104. Object.defineProperty(PerfCounter.prototype, "current", {
  10105. /**
  10106. * Returns the current value
  10107. */
  10108. get: function () {
  10109. return this._current;
  10110. },
  10111. enumerable: true,
  10112. configurable: true
  10113. });
  10114. Object.defineProperty(PerfCounter.prototype, "total", {
  10115. get: function () {
  10116. return this._totalAccumulated;
  10117. },
  10118. enumerable: true,
  10119. configurable: true
  10120. });
  10121. Object.defineProperty(PerfCounter.prototype, "count", {
  10122. get: function () {
  10123. return this._totalValueCount;
  10124. },
  10125. enumerable: true,
  10126. configurable: true
  10127. });
  10128. /**
  10129. * Call this method to start monitoring a new frame.
  10130. * 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.
  10131. */
  10132. PerfCounter.prototype.fetchNewFrame = function () {
  10133. this._totalValueCount++;
  10134. this._current = 0;
  10135. this._lastSecValueCount++;
  10136. };
  10137. /**
  10138. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10139. * @param newCount the count value to add to the monitored count
  10140. * @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.
  10141. */
  10142. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10143. if (!PerfCounter.Enabled) {
  10144. return;
  10145. }
  10146. this._current += newCount;
  10147. if (fetchResult) {
  10148. this._fetchResult();
  10149. }
  10150. };
  10151. /**
  10152. * Start monitoring this performance counter
  10153. */
  10154. PerfCounter.prototype.beginMonitoring = function () {
  10155. if (!PerfCounter.Enabled) {
  10156. return;
  10157. }
  10158. this._startMonitoringTime = Tools.Now;
  10159. };
  10160. /**
  10161. * Compute the time lapsed since the previous beginMonitoring() call.
  10162. * @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
  10163. */
  10164. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10165. if (newFrame === void 0) { newFrame = true; }
  10166. if (!PerfCounter.Enabled) {
  10167. return;
  10168. }
  10169. if (newFrame) {
  10170. this.fetchNewFrame();
  10171. }
  10172. var currentTime = Tools.Now;
  10173. this._current = currentTime - this._startMonitoringTime;
  10174. if (newFrame) {
  10175. this._fetchResult();
  10176. }
  10177. };
  10178. PerfCounter.prototype._fetchResult = function () {
  10179. this._totalAccumulated += this._current;
  10180. this._lastSecAccumulated += this._current;
  10181. // Min/Max update
  10182. this._min = Math.min(this._min, this._current);
  10183. this._max = Math.max(this._max, this._current);
  10184. this._average = this._totalAccumulated / this._totalValueCount;
  10185. // Reset last sec?
  10186. var now = Tools.Now;
  10187. if ((now - this._lastSecTime) > 1000) {
  10188. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10189. this._lastSecTime = now;
  10190. this._lastSecAccumulated = 0;
  10191. this._lastSecValueCount = 0;
  10192. }
  10193. };
  10194. PerfCounter.Enabled = true;
  10195. return PerfCounter;
  10196. }());
  10197. BABYLON.PerfCounter = PerfCounter;
  10198. /**
  10199. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10200. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10201. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10202. * @param name The name of the class, case should be preserved
  10203. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10204. */
  10205. function className(name, module) {
  10206. return function (target) {
  10207. target["__bjsclassName__"] = name;
  10208. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10209. };
  10210. }
  10211. BABYLON.className = className;
  10212. /**
  10213. * An implementation of a loop for asynchronous functions.
  10214. */
  10215. var AsyncLoop = /** @class */ (function () {
  10216. /**
  10217. * Constroctor.
  10218. * @param iterations the number of iterations.
  10219. * @param _fn the function to run each iteration
  10220. * @param _successCallback the callback that will be called upon succesful execution
  10221. * @param offset starting offset.
  10222. */
  10223. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10224. if (offset === void 0) { offset = 0; }
  10225. this.iterations = iterations;
  10226. this._fn = _fn;
  10227. this._successCallback = _successCallback;
  10228. this.index = offset - 1;
  10229. this._done = false;
  10230. }
  10231. /**
  10232. * Execute the next iteration. Must be called after the last iteration was finished.
  10233. */
  10234. AsyncLoop.prototype.executeNext = function () {
  10235. if (!this._done) {
  10236. if (this.index + 1 < this.iterations) {
  10237. ++this.index;
  10238. this._fn(this);
  10239. }
  10240. else {
  10241. this.breakLoop();
  10242. }
  10243. }
  10244. };
  10245. /**
  10246. * Break the loop and run the success callback.
  10247. */
  10248. AsyncLoop.prototype.breakLoop = function () {
  10249. this._done = true;
  10250. this._successCallback();
  10251. };
  10252. /**
  10253. * Helper function
  10254. */
  10255. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10256. if (offset === void 0) { offset = 0; }
  10257. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10258. loop.executeNext();
  10259. return loop;
  10260. };
  10261. /**
  10262. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10263. * @param iterations total number of iterations
  10264. * @param syncedIterations number of synchronous iterations in each async iteration.
  10265. * @param fn the function to call each iteration.
  10266. * @param callback a success call back that will be called when iterating stops.
  10267. * @param breakFunction a break condition (optional)
  10268. * @param timeout timeout settings for the setTimeout function. default - 0.
  10269. * @constructor
  10270. */
  10271. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10272. if (timeout === void 0) { timeout = 0; }
  10273. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10274. if (breakFunction && breakFunction())
  10275. loop.breakLoop();
  10276. else {
  10277. setTimeout(function () {
  10278. for (var i = 0; i < syncedIterations; ++i) {
  10279. var iteration = (loop.index * syncedIterations) + i;
  10280. if (iteration >= iterations)
  10281. break;
  10282. fn(iteration);
  10283. if (breakFunction && breakFunction()) {
  10284. loop.breakLoop();
  10285. break;
  10286. }
  10287. }
  10288. loop.executeNext();
  10289. }, timeout);
  10290. }
  10291. }, callback);
  10292. };
  10293. return AsyncLoop;
  10294. }());
  10295. BABYLON.AsyncLoop = AsyncLoop;
  10296. })(BABYLON || (BABYLON = {}));
  10297. //# sourceMappingURL=babylon.tools.js.map
  10298. var BABYLON;
  10299. (function (BABYLON) {
  10300. var PromiseStates;
  10301. (function (PromiseStates) {
  10302. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10303. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10304. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10305. })(PromiseStates || (PromiseStates = {}));
  10306. var FulFillmentAgregator = /** @class */ (function () {
  10307. function FulFillmentAgregator() {
  10308. this.count = 0;
  10309. this.target = 0;
  10310. this.results = [];
  10311. }
  10312. return FulFillmentAgregator;
  10313. }());
  10314. var InternalPromise = /** @class */ (function () {
  10315. function InternalPromise(resolver) {
  10316. var _this = this;
  10317. this._state = PromiseStates.Pending;
  10318. this._children = new Array();
  10319. this._rejectWasConsumed = false;
  10320. if (!resolver) {
  10321. return;
  10322. }
  10323. try {
  10324. resolver(function (value) {
  10325. _this._resolve(value);
  10326. }, function (reason) {
  10327. _this._reject(reason);
  10328. });
  10329. }
  10330. catch (e) {
  10331. this._reject(e);
  10332. }
  10333. }
  10334. Object.defineProperty(InternalPromise.prototype, "_result", {
  10335. get: function () {
  10336. return this._resultValue;
  10337. },
  10338. set: function (value) {
  10339. this._resultValue = value;
  10340. if (this._parent && this._parent._result === undefined) {
  10341. this._parent._result = value;
  10342. }
  10343. },
  10344. enumerable: true,
  10345. configurable: true
  10346. });
  10347. InternalPromise.prototype.catch = function (onRejected) {
  10348. return this.then(undefined, onRejected);
  10349. };
  10350. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10351. var _this = this;
  10352. var newPromise = new InternalPromise();
  10353. newPromise._onFulfilled = onFulfilled;
  10354. newPromise._onRejected = onRejected;
  10355. // Composition
  10356. this._children.push(newPromise);
  10357. newPromise._parent = this;
  10358. if (this._state !== PromiseStates.Pending) {
  10359. BABYLON.Tools.SetImmediate(function () {
  10360. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10361. var returnedValue = newPromise._resolve(_this._result);
  10362. if (returnedValue !== undefined && returnedValue !== null) {
  10363. if (returnedValue._state !== undefined) {
  10364. var returnedPromise = returnedValue;
  10365. newPromise._children.push(returnedPromise);
  10366. returnedPromise._parent = newPromise;
  10367. newPromise = returnedPromise;
  10368. }
  10369. else {
  10370. newPromise._result = returnedValue;
  10371. }
  10372. }
  10373. }
  10374. else {
  10375. newPromise._reject(_this._reason);
  10376. }
  10377. });
  10378. }
  10379. return newPromise;
  10380. };
  10381. InternalPromise.prototype._moveChildren = function (children) {
  10382. var _this = this;
  10383. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10384. this._children.forEach(function (child) {
  10385. child._parent = _this;
  10386. });
  10387. if (this._state === PromiseStates.Fulfilled) {
  10388. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10389. var child = _b[_i];
  10390. child._resolve(this._result);
  10391. }
  10392. }
  10393. else if (this._state === PromiseStates.Rejected) {
  10394. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10395. var child = _d[_c];
  10396. child._reject(this._reason);
  10397. }
  10398. }
  10399. var _a;
  10400. };
  10401. InternalPromise.prototype._resolve = function (value) {
  10402. try {
  10403. this._state = PromiseStates.Fulfilled;
  10404. var returnedValue = null;
  10405. if (this._onFulfilled) {
  10406. returnedValue = this._onFulfilled(value);
  10407. }
  10408. if (returnedValue !== undefined && returnedValue !== null) {
  10409. if (returnedValue._state !== undefined) {
  10410. // Transmit children
  10411. var returnedPromise = returnedValue;
  10412. returnedPromise._parent = this;
  10413. returnedPromise._moveChildren(this._children);
  10414. value = returnedPromise._result;
  10415. }
  10416. else {
  10417. value = returnedValue;
  10418. }
  10419. }
  10420. this._result = value;
  10421. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10422. var child = _a[_i];
  10423. child._resolve(value);
  10424. }
  10425. this._children.length = 0;
  10426. delete this._onFulfilled;
  10427. delete this._onRejected;
  10428. }
  10429. catch (e) {
  10430. this._reject(e, true);
  10431. }
  10432. };
  10433. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10434. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10435. this._state = PromiseStates.Rejected;
  10436. this._reason = reason;
  10437. if (this._onRejected && !onLocalThrow) {
  10438. try {
  10439. this._onRejected(reason);
  10440. this._rejectWasConsumed = true;
  10441. }
  10442. catch (e) {
  10443. reason = e;
  10444. }
  10445. }
  10446. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10447. var child = _a[_i];
  10448. if (this._rejectWasConsumed) {
  10449. child._resolve(null);
  10450. }
  10451. else {
  10452. child._reject(reason);
  10453. }
  10454. }
  10455. this._children.length = 0;
  10456. delete this._onFulfilled;
  10457. delete this._onRejected;
  10458. };
  10459. InternalPromise.resolve = function (value) {
  10460. var newPromise = new InternalPromise();
  10461. newPromise._resolve(value);
  10462. return newPromise;
  10463. };
  10464. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10465. promise.then(function (value) {
  10466. agregator.results[index] = value;
  10467. agregator.count++;
  10468. if (agregator.count === agregator.target) {
  10469. agregator.rootPromise._resolve(agregator.results);
  10470. }
  10471. return null;
  10472. }, function (reason) {
  10473. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10474. agregator.rootPromise._reject(reason);
  10475. }
  10476. });
  10477. };
  10478. InternalPromise.all = function (promises) {
  10479. var newPromise = new InternalPromise();
  10480. var agregator = new FulFillmentAgregator();
  10481. agregator.target = promises.length;
  10482. agregator.rootPromise = newPromise;
  10483. if (promises.length) {
  10484. for (var index = 0; index < promises.length; index++) {
  10485. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10486. }
  10487. }
  10488. else {
  10489. newPromise._resolve([]);
  10490. }
  10491. return newPromise;
  10492. };
  10493. InternalPromise.race = function (promises) {
  10494. var newPromise = new InternalPromise();
  10495. if (promises.length) {
  10496. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10497. var promise = promises_1[_i];
  10498. promise.then(function (value) {
  10499. if (newPromise) {
  10500. newPromise._resolve(value);
  10501. newPromise = null;
  10502. }
  10503. return null;
  10504. }, function (reason) {
  10505. if (newPromise) {
  10506. newPromise._reject(reason);
  10507. newPromise = null;
  10508. }
  10509. });
  10510. }
  10511. }
  10512. return newPromise;
  10513. };
  10514. return InternalPromise;
  10515. }());
  10516. /**
  10517. * Helper class that provides a small promise polyfill
  10518. */
  10519. var PromisePolyfill = /** @class */ (function () {
  10520. function PromisePolyfill() {
  10521. }
  10522. /**
  10523. * Static function used to check if the polyfill is required
  10524. * If this is the case then the function will inject the polyfill to window.Promise
  10525. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10526. */
  10527. PromisePolyfill.Apply = function (force) {
  10528. if (force === void 0) { force = false; }
  10529. if (force || typeof Promise === 'undefined') {
  10530. var root = window;
  10531. root.Promise = InternalPromise;
  10532. }
  10533. };
  10534. return PromisePolyfill;
  10535. }());
  10536. BABYLON.PromisePolyfill = PromisePolyfill;
  10537. })(BABYLON || (BABYLON = {}));
  10538. //# sourceMappingURL=babylon.promise.js.map
  10539. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10540. var BABYLON;
  10541. (function (BABYLON) {
  10542. /**
  10543. * Helper class to push actions to a pool of workers.
  10544. */
  10545. var WorkerPool = /** @class */ (function () {
  10546. /**
  10547. * Constructor
  10548. * @param workers Array of workers to use for actions
  10549. */
  10550. function WorkerPool(workers) {
  10551. this._pendingActions = new Array();
  10552. this._workerInfos = workers.map(function (worker) { return ({
  10553. worker: worker,
  10554. active: false
  10555. }); });
  10556. }
  10557. /**
  10558. * Terminates all workers and clears any pending actions.
  10559. */
  10560. WorkerPool.prototype.dispose = function () {
  10561. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10562. var workerInfo = _a[_i];
  10563. workerInfo.worker.terminate();
  10564. }
  10565. delete this._workerInfos;
  10566. delete this._pendingActions;
  10567. };
  10568. /**
  10569. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10570. * pended until a worker has completed its action.
  10571. * @param action The action to perform. Call onComplete when the action is complete.
  10572. */
  10573. WorkerPool.prototype.push = function (action) {
  10574. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10575. var workerInfo = _a[_i];
  10576. if (!workerInfo.active) {
  10577. this._execute(workerInfo, action);
  10578. return;
  10579. }
  10580. }
  10581. this._pendingActions.push(action);
  10582. };
  10583. WorkerPool.prototype._execute = function (workerInfo, action) {
  10584. var _this = this;
  10585. workerInfo.active = true;
  10586. action(workerInfo.worker, function () {
  10587. workerInfo.active = false;
  10588. var nextAction = _this._pendingActions.shift();
  10589. if (nextAction) {
  10590. _this._execute(workerInfo, nextAction);
  10591. }
  10592. });
  10593. };
  10594. return WorkerPool;
  10595. }());
  10596. BABYLON.WorkerPool = WorkerPool;
  10597. })(BABYLON || (BABYLON = {}));
  10598. //# sourceMappingURL=babylon.workerPool.js.map
  10599. var BABYLON;
  10600. (function (BABYLON) {
  10601. /**
  10602. * @hidden
  10603. **/
  10604. var _AlphaState = /** @class */ (function () {
  10605. /**
  10606. * Initializes the state.
  10607. */
  10608. function _AlphaState() {
  10609. this._isAlphaBlendDirty = false;
  10610. this._isBlendFunctionParametersDirty = false;
  10611. this._isBlendEquationParametersDirty = false;
  10612. this._isBlendConstantsDirty = false;
  10613. this._alphaBlend = false;
  10614. this._blendFunctionParameters = new Array(4);
  10615. this._blendEquationParameters = new Array(2);
  10616. this._blendConstants = new Array(4);
  10617. this.reset();
  10618. }
  10619. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10620. get: function () {
  10621. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10622. },
  10623. enumerable: true,
  10624. configurable: true
  10625. });
  10626. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10627. get: function () {
  10628. return this._alphaBlend;
  10629. },
  10630. set: function (value) {
  10631. if (this._alphaBlend === value) {
  10632. return;
  10633. }
  10634. this._alphaBlend = value;
  10635. this._isAlphaBlendDirty = true;
  10636. },
  10637. enumerable: true,
  10638. configurable: true
  10639. });
  10640. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10641. if (this._blendConstants[0] === r &&
  10642. this._blendConstants[1] === g &&
  10643. this._blendConstants[2] === b &&
  10644. this._blendConstants[3] === a) {
  10645. return;
  10646. }
  10647. this._blendConstants[0] = r;
  10648. this._blendConstants[1] = g;
  10649. this._blendConstants[2] = b;
  10650. this._blendConstants[3] = a;
  10651. this._isBlendConstantsDirty = true;
  10652. };
  10653. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10654. if (this._blendFunctionParameters[0] === value0 &&
  10655. this._blendFunctionParameters[1] === value1 &&
  10656. this._blendFunctionParameters[2] === value2 &&
  10657. this._blendFunctionParameters[3] === value3) {
  10658. return;
  10659. }
  10660. this._blendFunctionParameters[0] = value0;
  10661. this._blendFunctionParameters[1] = value1;
  10662. this._blendFunctionParameters[2] = value2;
  10663. this._blendFunctionParameters[3] = value3;
  10664. this._isBlendFunctionParametersDirty = true;
  10665. };
  10666. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10667. if (this._blendEquationParameters[0] === rgb &&
  10668. this._blendEquationParameters[1] === alpha) {
  10669. return;
  10670. }
  10671. this._blendEquationParameters[0] = rgb;
  10672. this._blendEquationParameters[1] = alpha;
  10673. this._isBlendEquationParametersDirty = true;
  10674. };
  10675. _AlphaState.prototype.reset = function () {
  10676. this._alphaBlend = false;
  10677. this._blendFunctionParameters[0] = null;
  10678. this._blendFunctionParameters[1] = null;
  10679. this._blendFunctionParameters[2] = null;
  10680. this._blendFunctionParameters[3] = null;
  10681. this._blendEquationParameters[0] = null;
  10682. this._blendEquationParameters[1] = null;
  10683. this._blendConstants[0] = null;
  10684. this._blendConstants[1] = null;
  10685. this._blendConstants[2] = null;
  10686. this._blendConstants[3] = null;
  10687. this._isAlphaBlendDirty = true;
  10688. this._isBlendFunctionParametersDirty = false;
  10689. this._isBlendEquationParametersDirty = false;
  10690. this._isBlendConstantsDirty = false;
  10691. };
  10692. _AlphaState.prototype.apply = function (gl) {
  10693. if (!this.isDirty) {
  10694. return;
  10695. }
  10696. // Alpha blend
  10697. if (this._isAlphaBlendDirty) {
  10698. if (this._alphaBlend) {
  10699. gl.enable(gl.BLEND);
  10700. }
  10701. else {
  10702. gl.disable(gl.BLEND);
  10703. }
  10704. this._isAlphaBlendDirty = false;
  10705. }
  10706. // Alpha function
  10707. if (this._isBlendFunctionParametersDirty) {
  10708. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10709. this._isBlendFunctionParametersDirty = false;
  10710. }
  10711. // Alpha equation
  10712. if (this._isBlendEquationParametersDirty) {
  10713. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10714. this._isBlendEquationParametersDirty = false;
  10715. }
  10716. // Constants
  10717. if (this._isBlendConstantsDirty) {
  10718. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10719. this._isBlendConstantsDirty = false;
  10720. }
  10721. };
  10722. return _AlphaState;
  10723. }());
  10724. BABYLON._AlphaState = _AlphaState;
  10725. })(BABYLON || (BABYLON = {}));
  10726. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10727. var BABYLON;
  10728. (function (BABYLON) {
  10729. /**
  10730. * @hidden
  10731. **/
  10732. var _DepthCullingState = /** @class */ (function () {
  10733. /**
  10734. * Initializes the state.
  10735. */
  10736. function _DepthCullingState() {
  10737. this._isDepthTestDirty = false;
  10738. this._isDepthMaskDirty = false;
  10739. this._isDepthFuncDirty = false;
  10740. this._isCullFaceDirty = false;
  10741. this._isCullDirty = false;
  10742. this._isZOffsetDirty = false;
  10743. this._isFrontFaceDirty = false;
  10744. this.reset();
  10745. }
  10746. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10747. get: function () {
  10748. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10749. },
  10750. enumerable: true,
  10751. configurable: true
  10752. });
  10753. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10754. get: function () {
  10755. return this._zOffset;
  10756. },
  10757. set: function (value) {
  10758. if (this._zOffset === value) {
  10759. return;
  10760. }
  10761. this._zOffset = value;
  10762. this._isZOffsetDirty = true;
  10763. },
  10764. enumerable: true,
  10765. configurable: true
  10766. });
  10767. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10768. get: function () {
  10769. return this._cullFace;
  10770. },
  10771. set: function (value) {
  10772. if (this._cullFace === value) {
  10773. return;
  10774. }
  10775. this._cullFace = value;
  10776. this._isCullFaceDirty = true;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10782. get: function () {
  10783. return this._cull;
  10784. },
  10785. set: function (value) {
  10786. if (this._cull === value) {
  10787. return;
  10788. }
  10789. this._cull = value;
  10790. this._isCullDirty = true;
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10796. get: function () {
  10797. return this._depthFunc;
  10798. },
  10799. set: function (value) {
  10800. if (this._depthFunc === value) {
  10801. return;
  10802. }
  10803. this._depthFunc = value;
  10804. this._isDepthFuncDirty = true;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10810. get: function () {
  10811. return this._depthMask;
  10812. },
  10813. set: function (value) {
  10814. if (this._depthMask === value) {
  10815. return;
  10816. }
  10817. this._depthMask = value;
  10818. this._isDepthMaskDirty = true;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10824. get: function () {
  10825. return this._depthTest;
  10826. },
  10827. set: function (value) {
  10828. if (this._depthTest === value) {
  10829. return;
  10830. }
  10831. this._depthTest = value;
  10832. this._isDepthTestDirty = true;
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10838. get: function () {
  10839. return this._frontFace;
  10840. },
  10841. set: function (value) {
  10842. if (this._frontFace === value) {
  10843. return;
  10844. }
  10845. this._frontFace = value;
  10846. this._isFrontFaceDirty = true;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. _DepthCullingState.prototype.reset = function () {
  10852. this._depthMask = true;
  10853. this._depthTest = true;
  10854. this._depthFunc = null;
  10855. this._cullFace = null;
  10856. this._cull = null;
  10857. this._zOffset = 0;
  10858. this._frontFace = null;
  10859. this._isDepthTestDirty = true;
  10860. this._isDepthMaskDirty = true;
  10861. this._isDepthFuncDirty = false;
  10862. this._isCullFaceDirty = false;
  10863. this._isCullDirty = false;
  10864. this._isZOffsetDirty = false;
  10865. this._isFrontFaceDirty = false;
  10866. };
  10867. _DepthCullingState.prototype.apply = function (gl) {
  10868. if (!this.isDirty) {
  10869. return;
  10870. }
  10871. // Cull
  10872. if (this._isCullDirty) {
  10873. if (this.cull) {
  10874. gl.enable(gl.CULL_FACE);
  10875. }
  10876. else {
  10877. gl.disable(gl.CULL_FACE);
  10878. }
  10879. this._isCullDirty = false;
  10880. }
  10881. // Cull face
  10882. if (this._isCullFaceDirty) {
  10883. gl.cullFace(this.cullFace);
  10884. this._isCullFaceDirty = false;
  10885. }
  10886. // Depth mask
  10887. if (this._isDepthMaskDirty) {
  10888. gl.depthMask(this.depthMask);
  10889. this._isDepthMaskDirty = false;
  10890. }
  10891. // Depth test
  10892. if (this._isDepthTestDirty) {
  10893. if (this.depthTest) {
  10894. gl.enable(gl.DEPTH_TEST);
  10895. }
  10896. else {
  10897. gl.disable(gl.DEPTH_TEST);
  10898. }
  10899. this._isDepthTestDirty = false;
  10900. }
  10901. // Depth func
  10902. if (this._isDepthFuncDirty) {
  10903. gl.depthFunc(this.depthFunc);
  10904. this._isDepthFuncDirty = false;
  10905. }
  10906. // zOffset
  10907. if (this._isZOffsetDirty) {
  10908. if (this.zOffset) {
  10909. gl.enable(gl.POLYGON_OFFSET_FILL);
  10910. gl.polygonOffset(this.zOffset, 0);
  10911. }
  10912. else {
  10913. gl.disable(gl.POLYGON_OFFSET_FILL);
  10914. }
  10915. this._isZOffsetDirty = false;
  10916. }
  10917. // Front face
  10918. if (this._isFrontFaceDirty) {
  10919. gl.frontFace(this.frontFace);
  10920. this._isFrontFaceDirty = false;
  10921. }
  10922. };
  10923. return _DepthCullingState;
  10924. }());
  10925. BABYLON._DepthCullingState = _DepthCullingState;
  10926. })(BABYLON || (BABYLON = {}));
  10927. //# sourceMappingURL=babylon.depthCullingState.js.map
  10928. var BABYLON;
  10929. (function (BABYLON) {
  10930. /**
  10931. * @hidden
  10932. **/
  10933. var _StencilState = /** @class */ (function () {
  10934. function _StencilState() {
  10935. this._isStencilTestDirty = false;
  10936. this._isStencilMaskDirty = false;
  10937. this._isStencilFuncDirty = false;
  10938. this._isStencilOpDirty = false;
  10939. this.reset();
  10940. }
  10941. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10942. get: function () {
  10943. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10944. },
  10945. enumerable: true,
  10946. configurable: true
  10947. });
  10948. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10949. get: function () {
  10950. return this._stencilFunc;
  10951. },
  10952. set: function (value) {
  10953. if (this._stencilFunc === value) {
  10954. return;
  10955. }
  10956. this._stencilFunc = value;
  10957. this._isStencilFuncDirty = true;
  10958. },
  10959. enumerable: true,
  10960. configurable: true
  10961. });
  10962. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10963. get: function () {
  10964. return this._stencilFuncRef;
  10965. },
  10966. set: function (value) {
  10967. if (this._stencilFuncRef === value) {
  10968. return;
  10969. }
  10970. this._stencilFuncRef = value;
  10971. this._isStencilFuncDirty = true;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10977. get: function () {
  10978. return this._stencilFuncMask;
  10979. },
  10980. set: function (value) {
  10981. if (this._stencilFuncMask === value) {
  10982. return;
  10983. }
  10984. this._stencilFuncMask = value;
  10985. this._isStencilFuncDirty = true;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10991. get: function () {
  10992. return this._stencilOpStencilFail;
  10993. },
  10994. set: function (value) {
  10995. if (this._stencilOpStencilFail === value) {
  10996. return;
  10997. }
  10998. this._stencilOpStencilFail = value;
  10999. this._isStencilOpDirty = true;
  11000. },
  11001. enumerable: true,
  11002. configurable: true
  11003. });
  11004. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11005. get: function () {
  11006. return this._stencilOpDepthFail;
  11007. },
  11008. set: function (value) {
  11009. if (this._stencilOpDepthFail === value) {
  11010. return;
  11011. }
  11012. this._stencilOpDepthFail = value;
  11013. this._isStencilOpDirty = true;
  11014. },
  11015. enumerable: true,
  11016. configurable: true
  11017. });
  11018. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11019. get: function () {
  11020. return this._stencilOpStencilDepthPass;
  11021. },
  11022. set: function (value) {
  11023. if (this._stencilOpStencilDepthPass === value) {
  11024. return;
  11025. }
  11026. this._stencilOpStencilDepthPass = value;
  11027. this._isStencilOpDirty = true;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11033. get: function () {
  11034. return this._stencilMask;
  11035. },
  11036. set: function (value) {
  11037. if (this._stencilMask === value) {
  11038. return;
  11039. }
  11040. this._stencilMask = value;
  11041. this._isStencilMaskDirty = true;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11047. get: function () {
  11048. return this._stencilTest;
  11049. },
  11050. set: function (value) {
  11051. if (this._stencilTest === value) {
  11052. return;
  11053. }
  11054. this._stencilTest = value;
  11055. this._isStencilTestDirty = true;
  11056. },
  11057. enumerable: true,
  11058. configurable: true
  11059. });
  11060. _StencilState.prototype.reset = function () {
  11061. this._stencilTest = false;
  11062. this._stencilMask = 0xFF;
  11063. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11064. this._stencilFuncRef = 1;
  11065. this._stencilFuncMask = 0xFF;
  11066. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11067. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11068. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11069. this._isStencilTestDirty = true;
  11070. this._isStencilMaskDirty = true;
  11071. this._isStencilFuncDirty = true;
  11072. this._isStencilOpDirty = true;
  11073. };
  11074. _StencilState.prototype.apply = function (gl) {
  11075. if (!this.isDirty) {
  11076. return;
  11077. }
  11078. // Stencil test
  11079. if (this._isStencilTestDirty) {
  11080. if (this.stencilTest) {
  11081. gl.enable(gl.STENCIL_TEST);
  11082. }
  11083. else {
  11084. gl.disable(gl.STENCIL_TEST);
  11085. }
  11086. this._isStencilTestDirty = false;
  11087. }
  11088. // Stencil mask
  11089. if (this._isStencilMaskDirty) {
  11090. gl.stencilMask(this.stencilMask);
  11091. this._isStencilMaskDirty = false;
  11092. }
  11093. // Stencil func
  11094. if (this._isStencilFuncDirty) {
  11095. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11096. this._isStencilFuncDirty = false;
  11097. }
  11098. // Stencil op
  11099. if (this._isStencilOpDirty) {
  11100. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11101. this._isStencilOpDirty = false;
  11102. }
  11103. };
  11104. return _StencilState;
  11105. }());
  11106. BABYLON._StencilState = _StencilState;
  11107. })(BABYLON || (BABYLON = {}));
  11108. //# sourceMappingURL=babylon.stencilState.js.map
  11109. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11110. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11111. s = arguments[i];
  11112. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11113. t[p] = s[p];
  11114. }
  11115. return t;
  11116. };
  11117. var BABYLON;
  11118. (function (BABYLON) {
  11119. /**
  11120. * Keeps track of all the buffer info used in engine.
  11121. */
  11122. var BufferPointer = /** @class */ (function () {
  11123. function BufferPointer() {
  11124. }
  11125. return BufferPointer;
  11126. }());
  11127. /**
  11128. * Interface for attribute information associated with buffer instanciation
  11129. */
  11130. var InstancingAttributeInfo = /** @class */ (function () {
  11131. function InstancingAttributeInfo() {
  11132. }
  11133. return InstancingAttributeInfo;
  11134. }());
  11135. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11136. /**
  11137. * Define options used to create a render target texture
  11138. */
  11139. var RenderTargetCreationOptions = /** @class */ (function () {
  11140. function RenderTargetCreationOptions() {
  11141. }
  11142. return RenderTargetCreationOptions;
  11143. }());
  11144. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11145. /**
  11146. * Define options used to create a depth texture
  11147. */
  11148. var DepthTextureCreationOptions = /** @class */ (function () {
  11149. function DepthTextureCreationOptions() {
  11150. }
  11151. return DepthTextureCreationOptions;
  11152. }());
  11153. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11154. /**
  11155. * Class used to describe the capabilities of the engine relatively to the current browser
  11156. */
  11157. var EngineCapabilities = /** @class */ (function () {
  11158. function EngineCapabilities() {
  11159. }
  11160. return EngineCapabilities;
  11161. }());
  11162. BABYLON.EngineCapabilities = EngineCapabilities;
  11163. /**
  11164. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11165. */
  11166. var Engine = /** @class */ (function () {
  11167. /**
  11168. * Creates a new engine
  11169. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11170. * @param antialias defines enable antialiasing (default: false)
  11171. * @param options defines further options to be sent to the getContext() function
  11172. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11173. */
  11174. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11175. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11176. var _this = this;
  11177. // Public members
  11178. /**
  11179. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11180. */
  11181. this.forcePOTTextures = false;
  11182. /**
  11183. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11184. */
  11185. this.isFullscreen = false;
  11186. /**
  11187. * Gets a boolean indicating if the pointer is currently locked
  11188. */
  11189. this.isPointerLock = false;
  11190. /**
  11191. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11192. */
  11193. this.cullBackFaces = true;
  11194. /**
  11195. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11196. */
  11197. this.renderEvenInBackground = true;
  11198. /**
  11199. * Gets or sets a boolean indicating that cache can be kept between frames
  11200. */
  11201. this.preventCacheWipeBetweenFrames = false;
  11202. /**
  11203. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11204. **/
  11205. this.enableOfflineSupport = false;
  11206. /**
  11207. * 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)
  11208. **/
  11209. this.disableManifestCheck = false;
  11210. /**
  11211. * Gets the list of created scenes
  11212. */
  11213. this.scenes = new Array();
  11214. /**
  11215. * Gets the list of created postprocesses
  11216. */
  11217. this.postProcesses = new Array();
  11218. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11219. this.validateShaderPrograms = false;
  11220. // Observables
  11221. /**
  11222. * Observable event triggered each time the rendering canvas is resized
  11223. */
  11224. this.onResizeObservable = new BABYLON.Observable();
  11225. /**
  11226. * Observable event triggered each time the canvas loses focus
  11227. */
  11228. this.onCanvasBlurObservable = new BABYLON.Observable();
  11229. /**
  11230. * Observable event triggered each time the canvas gains focus
  11231. */
  11232. this.onCanvasFocusObservable = new BABYLON.Observable();
  11233. /**
  11234. * Observable event triggered each time the canvas receives pointerout event
  11235. */
  11236. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11237. /**
  11238. * Observable event triggered before each texture is initialized
  11239. */
  11240. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11241. //WebVR
  11242. this._vrDisplay = undefined;
  11243. this._vrSupported = false;
  11244. this._vrExclusivePointerMode = false;
  11245. // Uniform buffers list
  11246. /**
  11247. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11248. */
  11249. this.disableUniformBuffers = false;
  11250. /** @hidden */
  11251. this._uniformBuffers = new Array();
  11252. // Observables
  11253. /**
  11254. * Observable raised when the engine begins a new frame
  11255. */
  11256. this.onBeginFrameObservable = new BABYLON.Observable();
  11257. /**
  11258. * Observable raised when the engine ends the current frame
  11259. */
  11260. this.onEndFrameObservable = new BABYLON.Observable();
  11261. /**
  11262. * Observable raised when the engine is about to compile a shader
  11263. */
  11264. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11265. /**
  11266. * Observable raised when the engine has jsut compiled a shader
  11267. */
  11268. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11269. this._windowIsBackground = false;
  11270. this._webGLVersion = 1.0;
  11271. /** @hidden */
  11272. this._badOS = false;
  11273. /** @hidden */
  11274. this._badDesktopOS = false;
  11275. /**
  11276. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11277. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11278. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11279. */
  11280. this.disableTextureBindingOptimization = false;
  11281. /**
  11282. * Observable signaled when VR display mode changes
  11283. */
  11284. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11285. /**
  11286. * Observable signaled when VR request present is complete
  11287. */
  11288. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11289. /**
  11290. * Observable signaled when VR request present starts
  11291. */
  11292. this.onVRRequestPresentStart = new BABYLON.Observable();
  11293. this._colorWrite = true;
  11294. /** @hidden */
  11295. this._drawCalls = new BABYLON.PerfCounter();
  11296. /** @hidden */
  11297. this._textureCollisions = new BABYLON.PerfCounter();
  11298. this._renderingQueueLaunched = false;
  11299. this._activeRenderLoops = new Array();
  11300. // Deterministic lockstepMaxSteps
  11301. this._deterministicLockstep = false;
  11302. this._lockstepMaxSteps = 4;
  11303. // Lost context
  11304. /**
  11305. * Observable signaled when a context lost event is raised
  11306. */
  11307. this.onContextLostObservable = new BABYLON.Observable();
  11308. /**
  11309. * Observable signaled when a context restored event is raised
  11310. */
  11311. this.onContextRestoredObservable = new BABYLON.Observable();
  11312. this._contextWasLost = false;
  11313. this._doNotHandleContextLost = false;
  11314. // FPS
  11315. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11316. this._fps = 60;
  11317. this._deltaTime = 0;
  11318. /**
  11319. * Turn this value on if you want to pause FPS computation when in background
  11320. */
  11321. this.disablePerformanceMonitorInBackground = false;
  11322. // States
  11323. /** @hidden */
  11324. this._depthCullingState = new BABYLON._DepthCullingState();
  11325. /** @hidden */
  11326. this._stencilState = new BABYLON._StencilState();
  11327. /** @hidden */
  11328. this._alphaState = new BABYLON._AlphaState();
  11329. /** @hidden */
  11330. this._alphaMode = Engine.ALPHA_DISABLE;
  11331. // Cache
  11332. this._internalTexturesCache = new Array();
  11333. /** @hidden */
  11334. this._activeChannel = 0;
  11335. this._currentTextureChannel = -1;
  11336. /** @hidden */
  11337. this._boundTexturesCache = {};
  11338. this._compiledEffects = {};
  11339. this._vertexAttribArraysEnabled = [];
  11340. this._uintIndicesCurrentlySet = false;
  11341. this._currentBoundBuffer = new Array();
  11342. /** @hidden */
  11343. this._currentFramebuffer = null;
  11344. this._currentBufferPointers = new Array();
  11345. this._currentInstanceLocations = new Array();
  11346. this._currentInstanceBuffers = new Array();
  11347. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11348. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11349. this._vaoRecordInProgress = false;
  11350. this._mustWipeVertexAttributes = false;
  11351. this._nextFreeTextureSlots = new Array();
  11352. this._maxSimultaneousTextures = 0;
  11353. this._activeRequests = new Array();
  11354. // Hardware supported Compressed Textures
  11355. this._texturesSupported = new Array();
  11356. /**
  11357. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11358. */
  11359. this.premultipliedAlpha = true;
  11360. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11361. this._onVRFullScreenTriggered = function () {
  11362. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11363. //get the old size before we change
  11364. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11365. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11366. //get the width and height, change the render size
  11367. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11368. _this.setHardwareScalingLevel(1);
  11369. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11370. }
  11371. else {
  11372. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11373. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11374. }
  11375. };
  11376. this._unpackFlipYCached = null;
  11377. this._boundUniforms = {};
  11378. // Register promises
  11379. BABYLON.PromisePolyfill.Apply();
  11380. var canvas = null;
  11381. Engine.Instances.push(this);
  11382. if (!canvasOrContext) {
  11383. return;
  11384. }
  11385. options = options || {};
  11386. if (canvasOrContext.getContext) {
  11387. canvas = canvasOrContext;
  11388. this._renderingCanvas = canvas;
  11389. if (antialias != null) {
  11390. options.antialias = antialias;
  11391. }
  11392. if (options.deterministicLockstep === undefined) {
  11393. options.deterministicLockstep = false;
  11394. }
  11395. if (options.lockstepMaxSteps === undefined) {
  11396. options.lockstepMaxSteps = 4;
  11397. }
  11398. if (options.preserveDrawingBuffer === undefined) {
  11399. options.preserveDrawingBuffer = false;
  11400. }
  11401. if (options.audioEngine === undefined) {
  11402. options.audioEngine = true;
  11403. }
  11404. if (options.stencil === undefined) {
  11405. options.stencil = true;
  11406. }
  11407. if (options.premultipliedAlpha === false) {
  11408. this.premultipliedAlpha = false;
  11409. }
  11410. this._deterministicLockstep = options.deterministicLockstep;
  11411. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11412. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11413. // Exceptions
  11414. if (navigator && navigator.userAgent) {
  11415. var ua = navigator.userAgent;
  11416. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11417. var exception = _a[_i];
  11418. var key = exception.key;
  11419. var targets = exception.targets;
  11420. if (ua.indexOf(key) > -1) {
  11421. if (exception.capture && exception.captureConstraint) {
  11422. var capture = exception.capture;
  11423. var constraint = exception.captureConstraint;
  11424. var regex = new RegExp(capture);
  11425. var matches = regex.exec(ua);
  11426. if (matches && matches.length > 0) {
  11427. var capturedValue = parseInt(matches[matches.length - 1]);
  11428. if (capturedValue >= constraint) {
  11429. continue;
  11430. }
  11431. }
  11432. }
  11433. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11434. var target = targets_1[_b];
  11435. switch (target) {
  11436. case "uniformBuffer":
  11437. this.disableUniformBuffers = true;
  11438. break;
  11439. case "textureBindingOptimization":
  11440. this.disableTextureBindingOptimization = true;
  11441. break;
  11442. }
  11443. }
  11444. }
  11445. }
  11446. }
  11447. // GL
  11448. if (!options.disableWebGL2Support) {
  11449. try {
  11450. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11451. if (this._gl) {
  11452. this._webGLVersion = 2.0;
  11453. }
  11454. }
  11455. catch (e) {
  11456. // Do nothing
  11457. }
  11458. }
  11459. if (!this._gl) {
  11460. if (!canvas) {
  11461. throw new Error("The provided canvas is null or undefined.");
  11462. }
  11463. try {
  11464. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11465. }
  11466. catch (e) {
  11467. throw new Error("WebGL not supported");
  11468. }
  11469. }
  11470. if (!this._gl) {
  11471. throw new Error("WebGL not supported");
  11472. }
  11473. this._onCanvasFocus = function () {
  11474. _this.onCanvasFocusObservable.notifyObservers(_this);
  11475. };
  11476. this._onCanvasBlur = function () {
  11477. _this.onCanvasBlurObservable.notifyObservers(_this);
  11478. };
  11479. canvas.addEventListener("focus", this._onCanvasFocus);
  11480. canvas.addEventListener("blur", this._onCanvasBlur);
  11481. this._onBlur = function () {
  11482. if (_this.disablePerformanceMonitorInBackground) {
  11483. _this._performanceMonitor.disable();
  11484. }
  11485. _this._windowIsBackground = true;
  11486. };
  11487. this._onFocus = function () {
  11488. if (_this.disablePerformanceMonitorInBackground) {
  11489. _this._performanceMonitor.enable();
  11490. }
  11491. _this._windowIsBackground = false;
  11492. };
  11493. this._onCanvasPointerOut = function (ev) {
  11494. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11495. };
  11496. window.addEventListener("blur", this._onBlur);
  11497. window.addEventListener("focus", this._onFocus);
  11498. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11499. // Context lost
  11500. if (!this._doNotHandleContextLost) {
  11501. this._onContextLost = function (evt) {
  11502. evt.preventDefault();
  11503. _this._contextWasLost = true;
  11504. BABYLON.Tools.Warn("WebGL context lost.");
  11505. _this.onContextLostObservable.notifyObservers(_this);
  11506. };
  11507. this._onContextRestored = function (evt) {
  11508. // Adding a timeout to avoid race condition at browser level
  11509. setTimeout(function () {
  11510. // Rebuild gl context
  11511. _this._initGLContext();
  11512. // Rebuild effects
  11513. _this._rebuildEffects();
  11514. // Rebuild textures
  11515. _this._rebuildInternalTextures();
  11516. // Rebuild buffers
  11517. _this._rebuildBuffers();
  11518. // Cache
  11519. _this.wipeCaches(true);
  11520. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11521. _this.onContextRestoredObservable.notifyObservers(_this);
  11522. _this._contextWasLost = false;
  11523. }, 0);
  11524. };
  11525. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11526. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11527. }
  11528. }
  11529. else {
  11530. this._gl = canvasOrContext;
  11531. this._renderingCanvas = this._gl.canvas;
  11532. if (this._gl.renderbufferStorageMultisample) {
  11533. this._webGLVersion = 2.0;
  11534. }
  11535. options.stencil = this._gl.getContextAttributes().stencil;
  11536. }
  11537. // Viewport
  11538. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11539. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11540. this.resize();
  11541. this._isStencilEnable = options.stencil ? true : false;
  11542. this._initGLContext();
  11543. if (canvas) {
  11544. // Fullscreen
  11545. this._onFullscreenChange = function () {
  11546. if (document.fullscreen !== undefined) {
  11547. _this.isFullscreen = document.fullscreen;
  11548. }
  11549. else if (document.mozFullScreen !== undefined) {
  11550. _this.isFullscreen = document.mozFullScreen;
  11551. }
  11552. else if (document.webkitIsFullScreen !== undefined) {
  11553. _this.isFullscreen = document.webkitIsFullScreen;
  11554. }
  11555. else if (document.msIsFullScreen !== undefined) {
  11556. _this.isFullscreen = document.msIsFullScreen;
  11557. }
  11558. // Pointer lock
  11559. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11560. canvas.requestPointerLock = canvas.requestPointerLock ||
  11561. canvas.msRequestPointerLock ||
  11562. canvas.mozRequestPointerLock ||
  11563. canvas.webkitRequestPointerLock;
  11564. if (canvas.requestPointerLock) {
  11565. canvas.requestPointerLock();
  11566. }
  11567. }
  11568. };
  11569. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11570. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11571. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11572. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11573. // Pointer lock
  11574. this._onPointerLockChange = function () {
  11575. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11576. document.webkitPointerLockElement === canvas ||
  11577. document.msPointerLockElement === canvas ||
  11578. document.pointerLockElement === canvas);
  11579. };
  11580. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11581. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11582. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11583. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11584. this._onVRDisplayPointerRestricted = function () {
  11585. if (canvas) {
  11586. canvas.requestPointerLock();
  11587. }
  11588. };
  11589. this._onVRDisplayPointerUnrestricted = function () {
  11590. document.exitPointerLock();
  11591. };
  11592. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11593. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11594. }
  11595. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11596. Engine.audioEngine = new BABYLON.AudioEngine();
  11597. }
  11598. // Prepare buffer pointers
  11599. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11600. this._currentBufferPointers[i] = new BufferPointer();
  11601. }
  11602. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11603. // Load WebVR Devices
  11604. if (options.autoEnableWebVR) {
  11605. this.initWebVR();
  11606. }
  11607. // Detect if we are running on a faulty buggy OS.
  11608. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11609. // Detect if we are running on a faulty buggy desktop OS.
  11610. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11611. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11612. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11613. }
  11614. Object.defineProperty(Engine, "LastCreatedEngine", {
  11615. /**
  11616. * Gets the latest created engine
  11617. */
  11618. get: function () {
  11619. if (Engine.Instances.length === 0) {
  11620. return null;
  11621. }
  11622. return Engine.Instances[Engine.Instances.length - 1];
  11623. },
  11624. enumerable: true,
  11625. configurable: true
  11626. });
  11627. Object.defineProperty(Engine, "LastCreatedScene", {
  11628. /**
  11629. * Gets the latest created scene
  11630. */
  11631. get: function () {
  11632. var lastCreatedEngine = Engine.LastCreatedEngine;
  11633. if (!lastCreatedEngine) {
  11634. return null;
  11635. }
  11636. if (lastCreatedEngine.scenes.length === 0) {
  11637. return null;
  11638. }
  11639. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11640. },
  11641. enumerable: true,
  11642. configurable: true
  11643. });
  11644. /**
  11645. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11646. * @param flag defines which part of the materials must be marked as dirty
  11647. * @param predicate defines a predicate used to filter which materials should be affected
  11648. */
  11649. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11650. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11651. var engine = Engine.Instances[engineIndex];
  11652. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11653. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11654. }
  11655. }
  11656. };
  11657. Object.defineProperty(Engine, "Version", {
  11658. /**
  11659. * Returns the current version of the framework
  11660. */
  11661. get: function () {
  11662. return "3.3.0-alpha.12";
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11668. /**
  11669. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11670. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11671. */
  11672. get: function () {
  11673. return this._vrExclusivePointerMode;
  11674. },
  11675. enumerable: true,
  11676. configurable: true
  11677. });
  11678. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11679. /**
  11680. * Gets a boolean indicating that the engine supports uniform buffers
  11681. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11682. */
  11683. get: function () {
  11684. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11685. },
  11686. enumerable: true,
  11687. configurable: true
  11688. });
  11689. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11690. /**
  11691. * Gets a boolean indicating that only power of 2 textures are supported
  11692. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11693. */
  11694. get: function () {
  11695. return this._webGLVersion < 2 || this.forcePOTTextures;
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11701. /**
  11702. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11703. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11704. */
  11705. get: function () {
  11706. return this._doNotHandleContextLost;
  11707. },
  11708. set: function (value) {
  11709. this._doNotHandleContextLost = value;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11715. /**
  11716. * Gets the performance monitor attached to this engine
  11717. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11718. */
  11719. get: function () {
  11720. return this._performanceMonitor;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11726. /**
  11727. * Gets the list of texture formats supported
  11728. */
  11729. get: function () {
  11730. return this._texturesSupported;
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11736. /**
  11737. * Gets the list of texture formats in use
  11738. */
  11739. get: function () {
  11740. return this._textureFormatInUse;
  11741. },
  11742. enumerable: true,
  11743. configurable: true
  11744. });
  11745. Object.defineProperty(Engine.prototype, "currentViewport", {
  11746. /**
  11747. * Gets the current viewport
  11748. */
  11749. get: function () {
  11750. return this._cachedViewport;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11756. /**
  11757. * Gets the default empty texture
  11758. */
  11759. get: function () {
  11760. if (!this._emptyTexture) {
  11761. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11762. }
  11763. return this._emptyTexture;
  11764. },
  11765. enumerable: true,
  11766. configurable: true
  11767. });
  11768. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11769. /**
  11770. * Gets the default empty 3D texture
  11771. */
  11772. get: function () {
  11773. if (!this._emptyTexture3D) {
  11774. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11775. }
  11776. return this._emptyTexture3D;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11782. /**
  11783. * Gets the default empty cube texture
  11784. */
  11785. get: function () {
  11786. if (!this._emptyCubeTexture) {
  11787. var faceData = new Uint8Array(4);
  11788. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11789. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11790. }
  11791. return this._emptyCubeTexture;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Engine.prototype._rebuildInternalTextures = function () {
  11797. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11798. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11799. var internalTexture = currentState_1[_i];
  11800. internalTexture._rebuild();
  11801. }
  11802. };
  11803. Engine.prototype._rebuildEffects = function () {
  11804. for (var key in this._compiledEffects) {
  11805. var effect = this._compiledEffects[key];
  11806. effect._prepareEffect();
  11807. }
  11808. BABYLON.Effect.ResetCache();
  11809. };
  11810. Engine.prototype._rebuildBuffers = function () {
  11811. // Index / Vertex
  11812. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11813. var scene = _a[_i];
  11814. scene.resetCachedMaterial();
  11815. scene._rebuildGeometries();
  11816. scene._rebuildTextures();
  11817. }
  11818. // Uniforms
  11819. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11820. var uniformBuffer = _c[_b];
  11821. uniformBuffer._rebuild();
  11822. }
  11823. };
  11824. Engine.prototype._initGLContext = function () {
  11825. // Caps
  11826. this._caps = new EngineCapabilities();
  11827. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11828. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11829. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11830. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11831. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11832. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11833. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11834. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11835. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11836. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11837. // Infos
  11838. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11839. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11840. if (rendererInfo != null) {
  11841. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11842. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11843. }
  11844. if (!this._glVendor) {
  11845. this._glVendor = "Unknown vendor";
  11846. }
  11847. if (!this._glRenderer) {
  11848. this._glRenderer = "Unknown renderer";
  11849. }
  11850. // Constants
  11851. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11852. if (this._gl.RGBA16F !== 0x881A) {
  11853. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11854. }
  11855. if (this._gl.RGBA32F !== 0x8814) {
  11856. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11857. }
  11858. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11859. this._gl.DEPTH24_STENCIL8 = 35056;
  11860. }
  11861. // Extensions
  11862. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11863. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11864. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11865. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11866. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11867. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11868. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11869. 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');
  11870. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11871. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11872. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11873. this._caps.highPrecisionShaderSupported = true;
  11874. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11875. if (this._caps.timerQuery) {
  11876. if (this._webGLVersion === 1) {
  11877. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11878. }
  11879. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11880. }
  11881. // Checks if some of the format renders first to allow the use of webgl inspector.
  11882. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11883. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11884. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11885. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11886. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11887. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11888. if (this._webGLVersion > 1) {
  11889. this._gl.HALF_FLOAT_OES = 0x140B;
  11890. }
  11891. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11892. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11893. // Draw buffers
  11894. if (this._webGLVersion > 1) {
  11895. this._caps.drawBuffersExtension = true;
  11896. }
  11897. else {
  11898. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11899. if (drawBuffersExtension !== null) {
  11900. this._caps.drawBuffersExtension = true;
  11901. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11902. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11903. for (var i = 0; i < 16; i++) {
  11904. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11905. }
  11906. }
  11907. else {
  11908. this._caps.drawBuffersExtension = false;
  11909. }
  11910. }
  11911. // Depth Texture
  11912. if (this._webGLVersion > 1) {
  11913. this._caps.depthTextureExtension = true;
  11914. }
  11915. else {
  11916. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11917. if (depthTextureExtension != null) {
  11918. this._caps.depthTextureExtension = true;
  11919. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11920. }
  11921. }
  11922. // Vertex array object
  11923. if (this._webGLVersion > 1) {
  11924. this._caps.vertexArrayObject = true;
  11925. }
  11926. else {
  11927. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11928. if (vertexArrayObjectExtension != null) {
  11929. this._caps.vertexArrayObject = true;
  11930. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11931. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11932. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11933. }
  11934. else {
  11935. this._caps.vertexArrayObject = false;
  11936. }
  11937. }
  11938. // Instances count
  11939. if (this._webGLVersion > 1) {
  11940. this._caps.instancedArrays = true;
  11941. }
  11942. else {
  11943. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11944. if (instanceExtension != null) {
  11945. this._caps.instancedArrays = true;
  11946. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11947. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11948. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11949. }
  11950. else {
  11951. this._caps.instancedArrays = false;
  11952. }
  11953. }
  11954. // Intelligently add supported compressed formats in order to check for.
  11955. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11956. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11957. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11958. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11959. if (this._caps.astc)
  11960. this.texturesSupported.push('-astc.ktx');
  11961. if (this._caps.s3tc)
  11962. this.texturesSupported.push('-dxt.ktx');
  11963. if (this._caps.pvrtc)
  11964. this.texturesSupported.push('-pvrtc.ktx');
  11965. if (this._caps.etc2)
  11966. this.texturesSupported.push('-etc2.ktx');
  11967. if (this._caps.etc1)
  11968. this.texturesSupported.push('-etc1.ktx');
  11969. if (this._gl.getShaderPrecisionFormat) {
  11970. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11971. if (highp) {
  11972. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11973. }
  11974. }
  11975. // Depth buffer
  11976. this.setDepthBuffer(true);
  11977. this.setDepthFunctionToLessOrEqual();
  11978. this.setDepthWrite(true);
  11979. // Texture maps
  11980. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11981. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11982. this._nextFreeTextureSlots.push(slot);
  11983. }
  11984. };
  11985. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11986. /**
  11987. * Gets version of the current webGL context
  11988. */
  11989. get: function () {
  11990. return this._webGLVersion;
  11991. },
  11992. enumerable: true,
  11993. configurable: true
  11994. });
  11995. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11996. /**
  11997. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11998. */
  11999. get: function () {
  12000. return this._isStencilEnable;
  12001. },
  12002. enumerable: true,
  12003. configurable: true
  12004. });
  12005. Engine.prototype._prepareWorkingCanvas = function () {
  12006. if (this._workingCanvas) {
  12007. return;
  12008. }
  12009. this._workingCanvas = document.createElement("canvas");
  12010. var context = this._workingCanvas.getContext("2d");
  12011. if (context) {
  12012. this._workingContext = context;
  12013. }
  12014. };
  12015. /**
  12016. * Reset the texture cache to empty state
  12017. */
  12018. Engine.prototype.resetTextureCache = function () {
  12019. for (var key in this._boundTexturesCache) {
  12020. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12021. continue;
  12022. }
  12023. var boundTexture = this._boundTexturesCache[key];
  12024. if (boundTexture) {
  12025. this._removeDesignatedSlot(boundTexture);
  12026. }
  12027. this._boundTexturesCache[key] = null;
  12028. }
  12029. if (!this.disableTextureBindingOptimization) {
  12030. this._nextFreeTextureSlots = [];
  12031. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12032. this._nextFreeTextureSlots.push(slot);
  12033. }
  12034. }
  12035. this._currentTextureChannel = -1;
  12036. };
  12037. /**
  12038. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12039. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12040. * @returns true if engine is in deterministic lock step mode
  12041. */
  12042. Engine.prototype.isDeterministicLockStep = function () {
  12043. return this._deterministicLockstep;
  12044. };
  12045. /**
  12046. * Gets the max steps when engine is running in deterministic lock step
  12047. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12048. * @returns the max steps
  12049. */
  12050. Engine.prototype.getLockstepMaxSteps = function () {
  12051. return this._lockstepMaxSteps;
  12052. };
  12053. /**
  12054. * Gets an object containing information about the current webGL context
  12055. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12056. */
  12057. Engine.prototype.getGlInfo = function () {
  12058. return {
  12059. vendor: this._glVendor,
  12060. renderer: this._glRenderer,
  12061. version: this._glVersion
  12062. };
  12063. };
  12064. /**
  12065. * Gets current aspect ratio
  12066. * @param camera defines the camera to use to get the aspect ratio
  12067. * @param useScreen defines if screen size must be used (or the current render target if any)
  12068. * @returns a number defining the aspect ratio
  12069. */
  12070. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12071. if (useScreen === void 0) { useScreen = false; }
  12072. var viewport = camera.viewport;
  12073. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12074. };
  12075. /**
  12076. * Gets current screen aspect ratio
  12077. * @returns a number defining the aspect ratio
  12078. */
  12079. Engine.prototype.getScreenAspectRatio = function () {
  12080. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12081. };
  12082. /**
  12083. * Gets the current render width
  12084. * @param useScreen defines if screen size must be used (or the current render target if any)
  12085. * @returns a number defining the current render width
  12086. */
  12087. Engine.prototype.getRenderWidth = function (useScreen) {
  12088. if (useScreen === void 0) { useScreen = false; }
  12089. if (!useScreen && this._currentRenderTarget) {
  12090. return this._currentRenderTarget.width;
  12091. }
  12092. return this._gl.drawingBufferWidth;
  12093. };
  12094. /**
  12095. * Gets the current render height
  12096. * @param useScreen defines if screen size must be used (or the current render target if any)
  12097. * @returns a number defining the current render height
  12098. */
  12099. Engine.prototype.getRenderHeight = function (useScreen) {
  12100. if (useScreen === void 0) { useScreen = false; }
  12101. if (!useScreen && this._currentRenderTarget) {
  12102. return this._currentRenderTarget.height;
  12103. }
  12104. return this._gl.drawingBufferHeight;
  12105. };
  12106. /**
  12107. * Gets the HTML canvas attached with the current webGL context
  12108. * @returns a HTML canvas
  12109. */
  12110. Engine.prototype.getRenderingCanvas = function () {
  12111. return this._renderingCanvas;
  12112. };
  12113. /**
  12114. * Gets the client rect of the HTML canvas attached with the current webGL context
  12115. * @returns a client rectanglee
  12116. */
  12117. Engine.prototype.getRenderingCanvasClientRect = function () {
  12118. if (!this._renderingCanvas) {
  12119. return null;
  12120. }
  12121. return this._renderingCanvas.getBoundingClientRect();
  12122. };
  12123. /**
  12124. * Defines the hardware scaling level.
  12125. * By default the hardware scaling level is computed from the window device ratio.
  12126. * 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.
  12127. * @param level defines the level to use
  12128. */
  12129. Engine.prototype.setHardwareScalingLevel = function (level) {
  12130. this._hardwareScalingLevel = level;
  12131. this.resize();
  12132. };
  12133. /**
  12134. * Gets the current hardware scaling level.
  12135. * By default the hardware scaling level is computed from the window device ratio.
  12136. * 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.
  12137. * @returns a number indicating the current hardware scaling level
  12138. */
  12139. Engine.prototype.getHardwareScalingLevel = function () {
  12140. return this._hardwareScalingLevel;
  12141. };
  12142. /**
  12143. * Gets the list of loaded textures
  12144. * @returns an array containing all loaded textures
  12145. */
  12146. Engine.prototype.getLoadedTexturesCache = function () {
  12147. return this._internalTexturesCache;
  12148. };
  12149. /**
  12150. * Gets the object containing all engine capabilities
  12151. * @returns the EngineCapabilities object
  12152. */
  12153. Engine.prototype.getCaps = function () {
  12154. return this._caps;
  12155. };
  12156. Object.defineProperty(Engine.prototype, "drawCalls", {
  12157. /** @hidden */
  12158. get: function () {
  12159. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12160. return 0;
  12161. },
  12162. enumerable: true,
  12163. configurable: true
  12164. });
  12165. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12166. /** @hidden */
  12167. get: function () {
  12168. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12169. return null;
  12170. },
  12171. enumerable: true,
  12172. configurable: true
  12173. });
  12174. /**
  12175. * Gets the current depth function
  12176. * @returns a number defining the depth function
  12177. */
  12178. Engine.prototype.getDepthFunction = function () {
  12179. return this._depthCullingState.depthFunc;
  12180. };
  12181. /**
  12182. * Sets the current depth function
  12183. * @param depthFunc defines the function to use
  12184. */
  12185. Engine.prototype.setDepthFunction = function (depthFunc) {
  12186. this._depthCullingState.depthFunc = depthFunc;
  12187. };
  12188. /**
  12189. * Sets the current depth function to GREATER
  12190. */
  12191. Engine.prototype.setDepthFunctionToGreater = function () {
  12192. this._depthCullingState.depthFunc = this._gl.GREATER;
  12193. };
  12194. /**
  12195. * Sets the current depth function to GEQUAL
  12196. */
  12197. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12198. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12199. };
  12200. /**
  12201. * Sets the current depth function to LESS
  12202. */
  12203. Engine.prototype.setDepthFunctionToLess = function () {
  12204. this._depthCullingState.depthFunc = this._gl.LESS;
  12205. };
  12206. /**
  12207. * Sets the current depth function to LEQUAL
  12208. */
  12209. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12210. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12211. };
  12212. /**
  12213. * Gets a boolean indicating if stencil buffer is enabled
  12214. * @returns the current stencil buffer state
  12215. */
  12216. Engine.prototype.getStencilBuffer = function () {
  12217. return this._stencilState.stencilTest;
  12218. };
  12219. /**
  12220. * Enable or disable the stencil buffer
  12221. * @param enable defines if the stencil buffer must be enabled or disabled
  12222. */
  12223. Engine.prototype.setStencilBuffer = function (enable) {
  12224. this._stencilState.stencilTest = enable;
  12225. };
  12226. /**
  12227. * Gets the current stencil mask
  12228. * @returns a number defining the new stencil mask to use
  12229. */
  12230. Engine.prototype.getStencilMask = function () {
  12231. return this._stencilState.stencilMask;
  12232. };
  12233. /**
  12234. * Sets the current stencil mask
  12235. * @param mask defines the new stencil mask to use
  12236. */
  12237. Engine.prototype.setStencilMask = function (mask) {
  12238. this._stencilState.stencilMask = mask;
  12239. };
  12240. /**
  12241. * Gets the current stencil function
  12242. * @returns a number defining the stencil function to use
  12243. */
  12244. Engine.prototype.getStencilFunction = function () {
  12245. return this._stencilState.stencilFunc;
  12246. };
  12247. /**
  12248. * Gets the current stencil reference value
  12249. * @returns a number defining the stencil reference value to use
  12250. */
  12251. Engine.prototype.getStencilFunctionReference = function () {
  12252. return this._stencilState.stencilFuncRef;
  12253. };
  12254. /**
  12255. * Gets the current stencil mask
  12256. * @returns a number defining the stencil mask to use
  12257. */
  12258. Engine.prototype.getStencilFunctionMask = function () {
  12259. return this._stencilState.stencilFuncMask;
  12260. };
  12261. /**
  12262. * Sets the current stencil function
  12263. * @param stencilFunc defines the new stencil function to use
  12264. */
  12265. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12266. this._stencilState.stencilFunc = stencilFunc;
  12267. };
  12268. /**
  12269. * Sets the current stencil reference
  12270. * @param reference defines the new stencil reference to use
  12271. */
  12272. Engine.prototype.setStencilFunctionReference = function (reference) {
  12273. this._stencilState.stencilFuncRef = reference;
  12274. };
  12275. /**
  12276. * Sets the current stencil mask
  12277. * @param mask defines the new stencil mask to use
  12278. */
  12279. Engine.prototype.setStencilFunctionMask = function (mask) {
  12280. this._stencilState.stencilFuncMask = mask;
  12281. };
  12282. /**
  12283. * Gets the current stencil operation when stencil fails
  12284. * @returns a number defining stencil operation to use when stencil fails
  12285. */
  12286. Engine.prototype.getStencilOperationFail = function () {
  12287. return this._stencilState.stencilOpStencilFail;
  12288. };
  12289. /**
  12290. * Gets the current stencil operation when depth fails
  12291. * @returns a number defining stencil operation to use when depth fails
  12292. */
  12293. Engine.prototype.getStencilOperationDepthFail = function () {
  12294. return this._stencilState.stencilOpDepthFail;
  12295. };
  12296. /**
  12297. * Gets the current stencil operation when stencil passes
  12298. * @returns a number defining stencil operation to use when stencil passes
  12299. */
  12300. Engine.prototype.getStencilOperationPass = function () {
  12301. return this._stencilState.stencilOpStencilDepthPass;
  12302. };
  12303. /**
  12304. * Sets the stencil operation to use when stencil fails
  12305. * @param operation defines the stencil operation to use when stencil fails
  12306. */
  12307. Engine.prototype.setStencilOperationFail = function (operation) {
  12308. this._stencilState.stencilOpStencilFail = operation;
  12309. };
  12310. /**
  12311. * Sets the stencil operation to use when depth fails
  12312. * @param operation defines the stencil operation to use when depth fails
  12313. */
  12314. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12315. this._stencilState.stencilOpDepthFail = operation;
  12316. };
  12317. /**
  12318. * Sets the stencil operation to use when stencil passes
  12319. * @param operation defines the stencil operation to use when stencil passes
  12320. */
  12321. Engine.prototype.setStencilOperationPass = function (operation) {
  12322. this._stencilState.stencilOpStencilDepthPass = operation;
  12323. };
  12324. /**
  12325. * Sets a boolean indicating if the dithering state is enabled or disabled
  12326. * @param value defines the dithering state
  12327. */
  12328. Engine.prototype.setDitheringState = function (value) {
  12329. if (value) {
  12330. this._gl.enable(this._gl.DITHER);
  12331. }
  12332. else {
  12333. this._gl.disable(this._gl.DITHER);
  12334. }
  12335. };
  12336. /**
  12337. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12338. * @param value defines the rasterizer state
  12339. */
  12340. Engine.prototype.setRasterizerState = function (value) {
  12341. if (value) {
  12342. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12343. }
  12344. else {
  12345. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12346. }
  12347. };
  12348. /**
  12349. * stop executing a render loop function and remove it from the execution array
  12350. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12351. */
  12352. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12353. if (!renderFunction) {
  12354. this._activeRenderLoops = [];
  12355. return;
  12356. }
  12357. var index = this._activeRenderLoops.indexOf(renderFunction);
  12358. if (index >= 0) {
  12359. this._activeRenderLoops.splice(index, 1);
  12360. }
  12361. };
  12362. /** @hidden */
  12363. Engine.prototype._renderLoop = function () {
  12364. if (!this._contextWasLost) {
  12365. var shouldRender = true;
  12366. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12367. shouldRender = false;
  12368. }
  12369. if (shouldRender) {
  12370. // Start new frame
  12371. this.beginFrame();
  12372. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12373. var renderFunction = this._activeRenderLoops[index];
  12374. renderFunction();
  12375. }
  12376. // Present
  12377. this.endFrame();
  12378. }
  12379. }
  12380. if (this._activeRenderLoops.length > 0) {
  12381. // Register new frame
  12382. var requester = null;
  12383. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12384. requester = this._vrDisplay;
  12385. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12386. }
  12387. else {
  12388. this._renderingQueueLaunched = false;
  12389. }
  12390. };
  12391. /**
  12392. * Register and execute a render loop. The engine can have more than one render function
  12393. * @param renderFunction defines the function to continuously execute
  12394. */
  12395. Engine.prototype.runRenderLoop = function (renderFunction) {
  12396. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12397. return;
  12398. }
  12399. this._activeRenderLoops.push(renderFunction);
  12400. if (!this._renderingQueueLaunched) {
  12401. this._renderingQueueLaunched = true;
  12402. this._bindedRenderFunction = this._renderLoop.bind(this);
  12403. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12404. }
  12405. };
  12406. /**
  12407. * Toggle full screen mode
  12408. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12409. * @param options defines an option object to be sent to the requestFullscreen function
  12410. */
  12411. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12412. if (this.isFullscreen) {
  12413. BABYLON.Tools.ExitFullscreen();
  12414. }
  12415. else {
  12416. this._pointerLockRequested = requestPointerLock;
  12417. if (this._renderingCanvas) {
  12418. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12419. }
  12420. }
  12421. };
  12422. /**
  12423. * Clear the current render buffer or the current render target (if any is set up)
  12424. * @param color defines the color to use
  12425. * @param backBuffer defines if the back buffer must be cleared
  12426. * @param depth defines if the depth buffer must be cleared
  12427. * @param stencil defines if the stencil buffer must be cleared
  12428. */
  12429. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12430. if (stencil === void 0) { stencil = false; }
  12431. this.applyStates();
  12432. var mode = 0;
  12433. if (backBuffer && color) {
  12434. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12435. mode |= this._gl.COLOR_BUFFER_BIT;
  12436. }
  12437. if (depth) {
  12438. this._gl.clearDepth(1.0);
  12439. mode |= this._gl.DEPTH_BUFFER_BIT;
  12440. }
  12441. if (stencil) {
  12442. this._gl.clearStencil(0);
  12443. mode |= this._gl.STENCIL_BUFFER_BIT;
  12444. }
  12445. this._gl.clear(mode);
  12446. };
  12447. /**
  12448. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12449. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12450. * @param y defines the y-coordinate of the corner of the clear rectangle
  12451. * @param width defines the width of the clear rectangle
  12452. * @param height defines the height of the clear rectangle
  12453. * @param clearColor defines the clear color
  12454. */
  12455. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12456. var gl = this._gl;
  12457. // Save state
  12458. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12459. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12460. // Change state
  12461. gl.enable(gl.SCISSOR_TEST);
  12462. gl.scissor(x, y, width, height);
  12463. // Clear
  12464. this.clear(clearColor, true, true, true);
  12465. // Restore state
  12466. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12467. if (curScissor === true) {
  12468. gl.enable(gl.SCISSOR_TEST);
  12469. }
  12470. else {
  12471. gl.disable(gl.SCISSOR_TEST);
  12472. }
  12473. };
  12474. /** @hidden */
  12475. Engine.prototype._viewport = function (x, y, width, height) {
  12476. if (x !== this._viewportCached.x ||
  12477. y !== this._viewportCached.y ||
  12478. width !== this._viewportCached.z ||
  12479. height !== this._viewportCached.w) {
  12480. this._viewportCached.x = x;
  12481. this._viewportCached.y = y;
  12482. this._viewportCached.z = width;
  12483. this._viewportCached.w = height;
  12484. this._gl.viewport(x, y, width, height);
  12485. }
  12486. };
  12487. /**
  12488. * Set the WebGL's viewport
  12489. * @param viewport defines the viewport element to be used
  12490. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12491. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12492. */
  12493. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12494. var width = requiredWidth || this.getRenderWidth();
  12495. var height = requiredHeight || this.getRenderHeight();
  12496. var x = viewport.x || 0;
  12497. var y = viewport.y || 0;
  12498. this._cachedViewport = viewport;
  12499. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12500. };
  12501. /**
  12502. * Directly set the WebGL Viewport
  12503. * @param x defines the x coordinate of the viewport (in screen space)
  12504. * @param y defines the y coordinate of the viewport (in screen space)
  12505. * @param width defines the width of the viewport (in screen space)
  12506. * @param height defines the height of the viewport (in screen space)
  12507. * @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
  12508. */
  12509. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12510. var currentViewport = this._cachedViewport;
  12511. this._cachedViewport = null;
  12512. this._viewport(x, y, width, height);
  12513. return currentViewport;
  12514. };
  12515. /**
  12516. * Begin a new frame
  12517. */
  12518. Engine.prototype.beginFrame = function () {
  12519. this.onBeginFrameObservable.notifyObservers(this);
  12520. this._measureFps();
  12521. };
  12522. /**
  12523. * Enf the current frame
  12524. */
  12525. Engine.prototype.endFrame = function () {
  12526. // Force a flush in case we are using a bad OS.
  12527. if (this._badOS) {
  12528. this.flushFramebuffer();
  12529. }
  12530. // Submit frame to the vr device, if enabled
  12531. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12532. // TODO: We should only submit the frame if we read frameData successfully.
  12533. this._vrDisplay.submitFrame();
  12534. }
  12535. this.onEndFrameObservable.notifyObservers(this);
  12536. };
  12537. /**
  12538. * Resize the view according to the canvas' size
  12539. */
  12540. Engine.prototype.resize = function () {
  12541. // We're not resizing the size of the canvas while in VR mode & presenting
  12542. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12543. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12544. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12545. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12546. }
  12547. };
  12548. /**
  12549. * Force a specific size of the canvas
  12550. * @param width defines the new canvas' width
  12551. * @param height defines the new canvas' height
  12552. */
  12553. Engine.prototype.setSize = function (width, height) {
  12554. if (!this._renderingCanvas) {
  12555. return;
  12556. }
  12557. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12558. return;
  12559. }
  12560. this._renderingCanvas.width = width;
  12561. this._renderingCanvas.height = height;
  12562. for (var index = 0; index < this.scenes.length; index++) {
  12563. var scene = this.scenes[index];
  12564. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12565. var cam = scene.cameras[camIndex];
  12566. cam._currentRenderId = 0;
  12567. }
  12568. }
  12569. if (this.onResizeObservable.hasObservers) {
  12570. this.onResizeObservable.notifyObservers(this);
  12571. }
  12572. };
  12573. // WebVR functions
  12574. /**
  12575. * Gets a boolean indicating if a webVR device was detected
  12576. * @returns true if a webVR device was detected
  12577. */
  12578. Engine.prototype.isVRDevicePresent = function () {
  12579. return !!this._vrDisplay;
  12580. };
  12581. /**
  12582. * Gets the current webVR device
  12583. * @returns the current webVR device (or null)
  12584. */
  12585. Engine.prototype.getVRDevice = function () {
  12586. return this._vrDisplay;
  12587. };
  12588. /**
  12589. * Initializes a webVR display and starts listening to display change events
  12590. * The onVRDisplayChangedObservable will be notified upon these changes
  12591. * @returns The onVRDisplayChangedObservable
  12592. */
  12593. Engine.prototype.initWebVR = function () {
  12594. this.initWebVRAsync();
  12595. return this.onVRDisplayChangedObservable;
  12596. };
  12597. /**
  12598. * Initializes a webVR display and starts listening to display change events
  12599. * The onVRDisplayChangedObservable will be notified upon these changes
  12600. * @returns A promise containing a VRDisplay and if vr is supported
  12601. */
  12602. Engine.prototype.initWebVRAsync = function () {
  12603. var _this = this;
  12604. var notifyObservers = function () {
  12605. var eventArgs = {
  12606. vrDisplay: _this._vrDisplay,
  12607. vrSupported: _this._vrSupported
  12608. };
  12609. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12610. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12611. };
  12612. if (!this._onVrDisplayConnect) {
  12613. this._onVrDisplayConnect = function (event) {
  12614. _this._vrDisplay = event.display;
  12615. notifyObservers();
  12616. };
  12617. this._onVrDisplayDisconnect = function () {
  12618. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12619. _this._vrDisplay = undefined;
  12620. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12621. notifyObservers();
  12622. };
  12623. this._onVrDisplayPresentChange = function () {
  12624. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12625. };
  12626. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12627. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12628. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12629. }
  12630. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12631. this._webVRInitPromise.then(notifyObservers);
  12632. return this._webVRInitPromise;
  12633. };
  12634. /**
  12635. * Call this function to switch to webVR mode
  12636. * Will do nothing if webVR is not supported or if there is no webVR device
  12637. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12638. */
  12639. Engine.prototype.enableVR = function () {
  12640. var _this = this;
  12641. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12642. var onResolved = function () {
  12643. _this.onVRRequestPresentComplete.notifyObservers(true);
  12644. _this._onVRFullScreenTriggered();
  12645. };
  12646. var onRejected = function () {
  12647. _this.onVRRequestPresentComplete.notifyObservers(false);
  12648. };
  12649. this.onVRRequestPresentStart.notifyObservers(this);
  12650. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12651. }
  12652. };
  12653. /**
  12654. * Call this function to leave webVR mode
  12655. * Will do nothing if webVR is not supported or if there is no webVR device
  12656. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12657. */
  12658. Engine.prototype.disableVR = function () {
  12659. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12660. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12661. }
  12662. };
  12663. Engine.prototype._getVRDisplaysAsync = function () {
  12664. var _this = this;
  12665. return new Promise(function (res, rej) {
  12666. if (navigator.getVRDisplays) {
  12667. navigator.getVRDisplays().then(function (devices) {
  12668. _this._vrSupported = true;
  12669. // note that devices may actually be an empty array. This is fine;
  12670. // we expect this._vrDisplay to be undefined in this case.
  12671. _this._vrDisplay = devices[0];
  12672. res({
  12673. vrDisplay: _this._vrDisplay,
  12674. vrSupported: _this._vrSupported
  12675. });
  12676. });
  12677. }
  12678. else {
  12679. _this._vrDisplay = undefined;
  12680. _this._vrSupported = false;
  12681. res({
  12682. vrDisplay: _this._vrDisplay,
  12683. vrSupported: _this._vrSupported
  12684. });
  12685. }
  12686. });
  12687. };
  12688. /**
  12689. * Binds the frame buffer to the specified texture.
  12690. * @param texture The texture to render to or null for the default canvas
  12691. * @param faceIndex The face of the texture to render to in case of cube texture
  12692. * @param requiredWidth The width of the target to render to
  12693. * @param requiredHeight The height of the target to render to
  12694. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12695. * @param depthStencilTexture The depth stencil texture to use to render
  12696. * @param lodLevel defines le lod level to bind to the frame buffer
  12697. */
  12698. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12699. if (lodLevel === void 0) { lodLevel = 0; }
  12700. if (this._currentRenderTarget) {
  12701. this.unBindFramebuffer(this._currentRenderTarget);
  12702. }
  12703. this._currentRenderTarget = texture;
  12704. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12705. var gl = this._gl;
  12706. if (texture.isCube) {
  12707. if (faceIndex === undefined) {
  12708. faceIndex = 0;
  12709. }
  12710. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12711. if (depthStencilTexture) {
  12712. if (depthStencilTexture._generateStencilBuffer) {
  12713. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12714. }
  12715. else {
  12716. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12717. }
  12718. }
  12719. }
  12720. if (this._cachedViewport && !forceFullscreenViewport) {
  12721. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12722. }
  12723. else {
  12724. if (!requiredWidth) {
  12725. requiredWidth = texture.width;
  12726. if (lodLevel) {
  12727. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12728. }
  12729. }
  12730. if (!requiredHeight) {
  12731. requiredHeight = texture.height;
  12732. if (lodLevel) {
  12733. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12734. }
  12735. }
  12736. this._viewport(0, 0, requiredWidth, requiredHeight);
  12737. }
  12738. this.wipeCaches();
  12739. };
  12740. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12741. if (this._currentFramebuffer !== framebuffer) {
  12742. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12743. this._currentFramebuffer = framebuffer;
  12744. }
  12745. };
  12746. /**
  12747. * Unbind the current render target texture from the webGL context
  12748. * @param texture defines the render target texture to unbind
  12749. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12750. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12751. */
  12752. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12753. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12754. this._currentRenderTarget = null;
  12755. // If MSAA, we need to bitblt back to main texture
  12756. var gl = this._gl;
  12757. if (texture._MSAAFramebuffer) {
  12758. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12759. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12760. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12761. }
  12762. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12763. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12764. gl.generateMipmap(gl.TEXTURE_2D);
  12765. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12766. }
  12767. if (onBeforeUnbind) {
  12768. if (texture._MSAAFramebuffer) {
  12769. // Bind the correct framebuffer
  12770. this.bindUnboundFramebuffer(texture._framebuffer);
  12771. }
  12772. onBeforeUnbind();
  12773. }
  12774. this.bindUnboundFramebuffer(null);
  12775. };
  12776. /**
  12777. * Unbind a list of render target textures from the webGL context
  12778. * This is used only when drawBuffer extension or webGL2 are active
  12779. * @param textures defines the render target textures to unbind
  12780. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12781. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12782. */
  12783. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12784. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12785. this._currentRenderTarget = null;
  12786. // If MSAA, we need to bitblt back to main texture
  12787. var gl = this._gl;
  12788. if (textures[0]._MSAAFramebuffer) {
  12789. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12790. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12791. var attachments = textures[0]._attachments;
  12792. if (!attachments) {
  12793. attachments = new Array(textures.length);
  12794. textures[0]._attachments = attachments;
  12795. }
  12796. for (var i = 0; i < textures.length; i++) {
  12797. var texture = textures[i];
  12798. for (var j = 0; j < attachments.length; j++) {
  12799. attachments[j] = gl.NONE;
  12800. }
  12801. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12802. gl.readBuffer(attachments[i]);
  12803. gl.drawBuffers(attachments);
  12804. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12805. }
  12806. for (var i = 0; i < attachments.length; i++) {
  12807. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12808. }
  12809. gl.drawBuffers(attachments);
  12810. }
  12811. for (var i = 0; i < textures.length; i++) {
  12812. var texture = textures[i];
  12813. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12814. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12815. gl.generateMipmap(gl.TEXTURE_2D);
  12816. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12817. }
  12818. }
  12819. if (onBeforeUnbind) {
  12820. if (textures[0]._MSAAFramebuffer) {
  12821. // Bind the correct framebuffer
  12822. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12823. }
  12824. onBeforeUnbind();
  12825. }
  12826. this.bindUnboundFramebuffer(null);
  12827. };
  12828. /**
  12829. * Force the mipmap generation for the given render target texture
  12830. * @param texture defines the render target texture to use
  12831. */
  12832. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12833. if (texture.generateMipMaps) {
  12834. var gl = this._gl;
  12835. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12836. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12837. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12838. }
  12839. };
  12840. /**
  12841. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12842. */
  12843. Engine.prototype.flushFramebuffer = function () {
  12844. this._gl.flush();
  12845. };
  12846. /**
  12847. * Unbind the current render target and bind the default framebuffer
  12848. */
  12849. Engine.prototype.restoreDefaultFramebuffer = function () {
  12850. if (this._currentRenderTarget) {
  12851. this.unBindFramebuffer(this._currentRenderTarget);
  12852. }
  12853. else {
  12854. this.bindUnboundFramebuffer(null);
  12855. }
  12856. if (this._cachedViewport) {
  12857. this.setViewport(this._cachedViewport);
  12858. }
  12859. this.wipeCaches();
  12860. };
  12861. // UBOs
  12862. /**
  12863. * Create an uniform buffer
  12864. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12865. * @param elements defines the content of the uniform buffer
  12866. * @returns the webGL uniform buffer
  12867. */
  12868. Engine.prototype.createUniformBuffer = function (elements) {
  12869. var ubo = this._gl.createBuffer();
  12870. if (!ubo) {
  12871. throw new Error("Unable to create uniform buffer");
  12872. }
  12873. this.bindUniformBuffer(ubo);
  12874. if (elements instanceof Float32Array) {
  12875. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12876. }
  12877. else {
  12878. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12879. }
  12880. this.bindUniformBuffer(null);
  12881. ubo.references = 1;
  12882. return ubo;
  12883. };
  12884. /**
  12885. * Create a dynamic uniform buffer
  12886. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12887. * @param elements defines the content of the uniform buffer
  12888. * @returns the webGL uniform buffer
  12889. */
  12890. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12891. var ubo = this._gl.createBuffer();
  12892. if (!ubo) {
  12893. throw new Error("Unable to create dynamic uniform buffer");
  12894. }
  12895. this.bindUniformBuffer(ubo);
  12896. if (elements instanceof Float32Array) {
  12897. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12898. }
  12899. else {
  12900. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12901. }
  12902. this.bindUniformBuffer(null);
  12903. ubo.references = 1;
  12904. return ubo;
  12905. };
  12906. /**
  12907. * Update an existing uniform buffer
  12908. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12909. * @param uniformBuffer defines the target uniform buffer
  12910. * @param elements defines the content to update
  12911. * @param offset defines the offset in the uniform buffer where update should start
  12912. * @param count defines the size of the data to update
  12913. */
  12914. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12915. this.bindUniformBuffer(uniformBuffer);
  12916. if (offset === undefined) {
  12917. offset = 0;
  12918. }
  12919. if (count === undefined) {
  12920. if (elements instanceof Float32Array) {
  12921. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12922. }
  12923. else {
  12924. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12925. }
  12926. }
  12927. else {
  12928. if (elements instanceof Float32Array) {
  12929. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12930. }
  12931. else {
  12932. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12933. }
  12934. }
  12935. this.bindUniformBuffer(null);
  12936. };
  12937. // VBOs
  12938. Engine.prototype._resetVertexBufferBinding = function () {
  12939. this.bindArrayBuffer(null);
  12940. this._cachedVertexBuffers = null;
  12941. };
  12942. /**
  12943. * Creates a vertex buffer
  12944. * @param data the data for the vertex buffer
  12945. * @returns the new WebGL static buffer
  12946. */
  12947. Engine.prototype.createVertexBuffer = function (data) {
  12948. var vbo = this._gl.createBuffer();
  12949. if (!vbo) {
  12950. throw new Error("Unable to create vertex buffer");
  12951. }
  12952. this.bindArrayBuffer(vbo);
  12953. if (data instanceof Array) {
  12954. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12955. }
  12956. else {
  12957. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12958. }
  12959. this._resetVertexBufferBinding();
  12960. vbo.references = 1;
  12961. return vbo;
  12962. };
  12963. /**
  12964. * Creates a dynamic vertex buffer
  12965. * @param data the data for the dynamic vertex buffer
  12966. * @returns the new WebGL dynamic buffer
  12967. */
  12968. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12969. var vbo = this._gl.createBuffer();
  12970. if (!vbo) {
  12971. throw new Error("Unable to create dynamic vertex buffer");
  12972. }
  12973. this.bindArrayBuffer(vbo);
  12974. if (data instanceof Array) {
  12975. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12976. }
  12977. else {
  12978. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12979. }
  12980. this._resetVertexBufferBinding();
  12981. vbo.references = 1;
  12982. return vbo;
  12983. };
  12984. /**
  12985. * Update a dynamic index buffer
  12986. * @param indexBuffer defines the target index buffer
  12987. * @param indices defines the data to update
  12988. * @param offset defines the offset in the target index buffer where update should start
  12989. */
  12990. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12991. if (offset === void 0) { offset = 0; }
  12992. // Force cache update
  12993. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12994. this.bindIndexBuffer(indexBuffer);
  12995. var arrayBuffer;
  12996. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12997. arrayBuffer = indices;
  12998. }
  12999. else {
  13000. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13001. }
  13002. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13003. this._resetIndexBufferBinding();
  13004. };
  13005. /**
  13006. * Updates a dynamic vertex buffer.
  13007. * @param vertexBuffer the vertex buffer to update
  13008. * @param data the data used to update the vertex buffer
  13009. * @param byteOffset the byte offset of the data
  13010. * @param byteLength the byte length of the data
  13011. */
  13012. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13013. this.bindArrayBuffer(vertexBuffer);
  13014. if (byteOffset === undefined) {
  13015. byteOffset = 0;
  13016. }
  13017. if (byteLength === undefined) {
  13018. if (data instanceof Array) {
  13019. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13020. }
  13021. else {
  13022. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13023. }
  13024. }
  13025. else {
  13026. if (data instanceof Array) {
  13027. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13028. }
  13029. else {
  13030. if (data instanceof ArrayBuffer) {
  13031. data = new Uint8Array(data, byteOffset, byteLength);
  13032. }
  13033. else {
  13034. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13035. }
  13036. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13037. }
  13038. }
  13039. this._resetVertexBufferBinding();
  13040. };
  13041. Engine.prototype._resetIndexBufferBinding = function () {
  13042. this.bindIndexBuffer(null);
  13043. this._cachedIndexBuffer = null;
  13044. };
  13045. /**
  13046. * Creates a new index buffer
  13047. * @param indices defines the content of the index buffer
  13048. * @param updatable defines if the index buffer must be updatable
  13049. * @returns a new webGL buffer
  13050. */
  13051. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13052. var vbo = this._gl.createBuffer();
  13053. if (!vbo) {
  13054. throw new Error("Unable to create index buffer");
  13055. }
  13056. this.bindIndexBuffer(vbo);
  13057. // Check for 32 bits indices
  13058. var arrayBuffer;
  13059. var need32Bits = false;
  13060. if (indices instanceof Uint16Array) {
  13061. arrayBuffer = indices;
  13062. }
  13063. else {
  13064. //check 32 bit support
  13065. if (this._caps.uintIndices) {
  13066. if (indices instanceof Uint32Array) {
  13067. arrayBuffer = indices;
  13068. need32Bits = true;
  13069. }
  13070. else {
  13071. //number[] or Int32Array, check if 32 bit is necessary
  13072. for (var index = 0; index < indices.length; index++) {
  13073. if (indices[index] > 65535) {
  13074. need32Bits = true;
  13075. break;
  13076. }
  13077. }
  13078. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13079. }
  13080. }
  13081. else {
  13082. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13083. arrayBuffer = new Uint16Array(indices);
  13084. }
  13085. }
  13086. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13087. this._resetIndexBufferBinding();
  13088. vbo.references = 1;
  13089. vbo.is32Bits = need32Bits;
  13090. return vbo;
  13091. };
  13092. /**
  13093. * Bind a webGL buffer to the webGL context
  13094. * @param buffer defines the buffer to bind
  13095. */
  13096. Engine.prototype.bindArrayBuffer = function (buffer) {
  13097. if (!this._vaoRecordInProgress) {
  13098. this._unbindVertexArrayObject();
  13099. }
  13100. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13101. };
  13102. /**
  13103. * Bind an uniform buffer to the current webGL context
  13104. * @param buffer defines the buffer to bind
  13105. */
  13106. Engine.prototype.bindUniformBuffer = function (buffer) {
  13107. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13108. };
  13109. /**
  13110. * Bind a buffer to the current webGL context at a given location
  13111. * @param buffer defines the buffer to bind
  13112. * @param location defines the index where to bind the buffer
  13113. */
  13114. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13115. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13116. };
  13117. /**
  13118. * Bind a specific block at a given index in a specific shader program
  13119. * @param shaderProgram defines the shader program
  13120. * @param blockName defines the block name
  13121. * @param index defines the index where to bind the block
  13122. */
  13123. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13124. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13125. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13126. };
  13127. ;
  13128. Engine.prototype.bindIndexBuffer = function (buffer) {
  13129. if (!this._vaoRecordInProgress) {
  13130. this._unbindVertexArrayObject();
  13131. }
  13132. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13133. };
  13134. Engine.prototype.bindBuffer = function (buffer, target) {
  13135. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13136. this._gl.bindBuffer(target, buffer);
  13137. this._currentBoundBuffer[target] = buffer;
  13138. }
  13139. };
  13140. /**
  13141. * update the bound buffer with the given data
  13142. * @param data defines the data to update
  13143. */
  13144. Engine.prototype.updateArrayBuffer = function (data) {
  13145. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13146. };
  13147. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13148. var pointer = this._currentBufferPointers[indx];
  13149. var changed = false;
  13150. if (!pointer.active) {
  13151. changed = true;
  13152. pointer.active = true;
  13153. pointer.index = indx;
  13154. pointer.size = size;
  13155. pointer.type = type;
  13156. pointer.normalized = normalized;
  13157. pointer.stride = stride;
  13158. pointer.offset = offset;
  13159. pointer.buffer = buffer;
  13160. }
  13161. else {
  13162. if (pointer.buffer !== buffer) {
  13163. pointer.buffer = buffer;
  13164. changed = true;
  13165. }
  13166. if (pointer.size !== size) {
  13167. pointer.size = size;
  13168. changed = true;
  13169. }
  13170. if (pointer.type !== type) {
  13171. pointer.type = type;
  13172. changed = true;
  13173. }
  13174. if (pointer.normalized !== normalized) {
  13175. pointer.normalized = normalized;
  13176. changed = true;
  13177. }
  13178. if (pointer.stride !== stride) {
  13179. pointer.stride = stride;
  13180. changed = true;
  13181. }
  13182. if (pointer.offset !== offset) {
  13183. pointer.offset = offset;
  13184. changed = true;
  13185. }
  13186. }
  13187. if (changed || this._vaoRecordInProgress) {
  13188. this.bindArrayBuffer(buffer);
  13189. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13190. }
  13191. };
  13192. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13193. if (indexBuffer == null) {
  13194. return;
  13195. }
  13196. if (this._cachedIndexBuffer !== indexBuffer) {
  13197. this._cachedIndexBuffer = indexBuffer;
  13198. this.bindIndexBuffer(indexBuffer);
  13199. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13200. }
  13201. };
  13202. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13203. var attributes = effect.getAttributesNames();
  13204. if (!this._vaoRecordInProgress) {
  13205. this._unbindVertexArrayObject();
  13206. }
  13207. this.unbindAllAttributes();
  13208. for (var index = 0; index < attributes.length; index++) {
  13209. var order = effect.getAttributeLocation(index);
  13210. if (order >= 0) {
  13211. var vertexBuffer = vertexBuffers[attributes[index]];
  13212. if (!vertexBuffer) {
  13213. continue;
  13214. }
  13215. this._gl.enableVertexAttribArray(order);
  13216. if (!this._vaoRecordInProgress) {
  13217. this._vertexAttribArraysEnabled[order] = true;
  13218. }
  13219. var buffer = vertexBuffer.getBuffer();
  13220. if (buffer) {
  13221. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13222. if (vertexBuffer.getIsInstanced()) {
  13223. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13224. if (!this._vaoRecordInProgress) {
  13225. this._currentInstanceLocations.push(order);
  13226. this._currentInstanceBuffers.push(buffer);
  13227. }
  13228. }
  13229. }
  13230. }
  13231. }
  13232. };
  13233. /**
  13234. * Records a vertex array object
  13235. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13236. * @param vertexBuffers defines the list of vertex buffers to store
  13237. * @param indexBuffer defines the index buffer to store
  13238. * @param effect defines the effect to store
  13239. * @returns the new vertex array object
  13240. */
  13241. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13242. var vao = this._gl.createVertexArray();
  13243. this._vaoRecordInProgress = true;
  13244. this._gl.bindVertexArray(vao);
  13245. this._mustWipeVertexAttributes = true;
  13246. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13247. this.bindIndexBuffer(indexBuffer);
  13248. this._vaoRecordInProgress = false;
  13249. this._gl.bindVertexArray(null);
  13250. return vao;
  13251. };
  13252. /**
  13253. * Bind a specific vertex array object
  13254. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13255. * @param vertexArrayObject defines the vertex array object to bind
  13256. * @param indexBuffer defines the index buffer to bind
  13257. */
  13258. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13259. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13260. this._cachedVertexArrayObject = vertexArrayObject;
  13261. this._gl.bindVertexArray(vertexArrayObject);
  13262. this._cachedVertexBuffers = null;
  13263. this._cachedIndexBuffer = null;
  13264. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13265. this._mustWipeVertexAttributes = true;
  13266. }
  13267. };
  13268. /**
  13269. * Bind webGl buffers directly to the webGL context
  13270. * @param vertexBuffer defines the vertex buffer to bind
  13271. * @param indexBuffer defines the index buffer to bind
  13272. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13273. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13274. * @param effect defines the effect associated with the vertex buffer
  13275. */
  13276. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13277. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13278. this._cachedVertexBuffers = vertexBuffer;
  13279. this._cachedEffectForVertexBuffers = effect;
  13280. var attributesCount = effect.getAttributesCount();
  13281. this._unbindVertexArrayObject();
  13282. this.unbindAllAttributes();
  13283. var offset = 0;
  13284. for (var index = 0; index < attributesCount; index++) {
  13285. if (index < vertexDeclaration.length) {
  13286. var order = effect.getAttributeLocation(index);
  13287. if (order >= 0) {
  13288. this._gl.enableVertexAttribArray(order);
  13289. this._vertexAttribArraysEnabled[order] = true;
  13290. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13291. }
  13292. offset += vertexDeclaration[index] * 4;
  13293. }
  13294. }
  13295. }
  13296. this._bindIndexBufferWithCache(indexBuffer);
  13297. };
  13298. Engine.prototype._unbindVertexArrayObject = function () {
  13299. if (!this._cachedVertexArrayObject) {
  13300. return;
  13301. }
  13302. this._cachedVertexArrayObject = null;
  13303. this._gl.bindVertexArray(null);
  13304. };
  13305. /**
  13306. * Bind a list of vertex buffers to the webGL context
  13307. * @param vertexBuffers defines the list of vertex buffers to bind
  13308. * @param indexBuffer defines the index buffer to bind
  13309. * @param effect defines the effect associated with the vertex buffers
  13310. */
  13311. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13312. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13313. this._cachedVertexBuffers = vertexBuffers;
  13314. this._cachedEffectForVertexBuffers = effect;
  13315. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13316. }
  13317. this._bindIndexBufferWithCache(indexBuffer);
  13318. };
  13319. /**
  13320. * Unbind all instance attributes
  13321. */
  13322. Engine.prototype.unbindInstanceAttributes = function () {
  13323. var boundBuffer;
  13324. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13325. var instancesBuffer = this._currentInstanceBuffers[i];
  13326. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13327. boundBuffer = instancesBuffer;
  13328. this.bindArrayBuffer(instancesBuffer);
  13329. }
  13330. var offsetLocation = this._currentInstanceLocations[i];
  13331. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13332. }
  13333. this._currentInstanceBuffers.length = 0;
  13334. this._currentInstanceLocations.length = 0;
  13335. };
  13336. /**
  13337. * Release and free the memory of a vertex array object
  13338. * @param vao defines the vertex array object to delete
  13339. */
  13340. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13341. this._gl.deleteVertexArray(vao);
  13342. };
  13343. /** @hidden */
  13344. Engine.prototype._releaseBuffer = function (buffer) {
  13345. buffer.references--;
  13346. if (buffer.references === 0) {
  13347. this._gl.deleteBuffer(buffer);
  13348. return true;
  13349. }
  13350. return false;
  13351. };
  13352. /**
  13353. * Creates a webGL buffer to use with instanciation
  13354. * @param capacity defines the size of the buffer
  13355. * @returns the webGL buffer
  13356. */
  13357. Engine.prototype.createInstancesBuffer = function (capacity) {
  13358. var buffer = this._gl.createBuffer();
  13359. if (!buffer) {
  13360. throw new Error("Unable to create instance buffer");
  13361. }
  13362. buffer.capacity = capacity;
  13363. this.bindArrayBuffer(buffer);
  13364. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13365. return buffer;
  13366. };
  13367. /**
  13368. * Delete a webGL buffer used with instanciation
  13369. * @param buffer defines the webGL buffer to delete
  13370. */
  13371. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13372. this._gl.deleteBuffer(buffer);
  13373. };
  13374. /**
  13375. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13376. * @param instancesBuffer defines the webGL buffer to update and bind
  13377. * @param data defines the data to store in the buffer
  13378. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13379. */
  13380. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13381. this.bindArrayBuffer(instancesBuffer);
  13382. if (data) {
  13383. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13384. }
  13385. if (offsetLocations[0].index !== undefined) {
  13386. var stride = 0;
  13387. for (var i = 0; i < offsetLocations.length; i++) {
  13388. var ai = offsetLocations[i];
  13389. stride += ai.attributeSize * 4;
  13390. }
  13391. for (var i = 0; i < offsetLocations.length; i++) {
  13392. var ai = offsetLocations[i];
  13393. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13394. this._gl.enableVertexAttribArray(ai.index);
  13395. this._vertexAttribArraysEnabled[ai.index] = true;
  13396. }
  13397. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13398. this._gl.vertexAttribDivisor(ai.index, 1);
  13399. this._currentInstanceLocations.push(ai.index);
  13400. this._currentInstanceBuffers.push(instancesBuffer);
  13401. }
  13402. }
  13403. else {
  13404. for (var index = 0; index < 4; index++) {
  13405. var offsetLocation = offsetLocations[index];
  13406. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13407. this._gl.enableVertexAttribArray(offsetLocation);
  13408. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13409. }
  13410. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13411. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13412. this._currentInstanceLocations.push(offsetLocation);
  13413. this._currentInstanceBuffers.push(instancesBuffer);
  13414. }
  13415. }
  13416. };
  13417. /**
  13418. * Apply all cached states (depth, culling, stencil and alpha)
  13419. */
  13420. Engine.prototype.applyStates = function () {
  13421. this._depthCullingState.apply(this._gl);
  13422. this._stencilState.apply(this._gl);
  13423. this._alphaState.apply(this._gl);
  13424. };
  13425. /**
  13426. * Send a draw order
  13427. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13428. * @param indexStart defines the starting index
  13429. * @param indexCount defines the number of index to draw
  13430. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13431. */
  13432. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13433. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13434. };
  13435. /**
  13436. * Draw a list of points
  13437. * @param verticesStart defines the index of first vertex to draw
  13438. * @param verticesCount defines the count of vertices to draw
  13439. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13440. */
  13441. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13442. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13443. };
  13444. /**
  13445. * Draw a list of unindexed primitives
  13446. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13447. * @param verticesStart defines the index of first vertex to draw
  13448. * @param verticesCount defines the count of vertices to draw
  13449. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13450. */
  13451. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13452. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13453. };
  13454. /**
  13455. * Draw a list of indexed primitives
  13456. * @param fillMode defines the primitive to use
  13457. * @param indexStart defines the starting index
  13458. * @param indexCount defines the number of index to draw
  13459. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13460. */
  13461. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13462. // Apply states
  13463. this.applyStates();
  13464. this._drawCalls.addCount(1, false);
  13465. // Render
  13466. var drawMode = this._drawMode(fillMode);
  13467. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13468. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13469. if (instancesCount) {
  13470. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13471. }
  13472. else {
  13473. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13474. }
  13475. };
  13476. /**
  13477. * Draw a list of unindexed primitives
  13478. * @param fillMode defines the primitive to use
  13479. * @param verticesStart defines the index of first vertex to draw
  13480. * @param verticesCount defines the count of vertices to draw
  13481. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13482. */
  13483. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13484. // Apply states
  13485. this.applyStates();
  13486. this._drawCalls.addCount(1, false);
  13487. var drawMode = this._drawMode(fillMode);
  13488. if (instancesCount) {
  13489. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13490. }
  13491. else {
  13492. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13493. }
  13494. };
  13495. Engine.prototype._drawMode = function (fillMode) {
  13496. switch (fillMode) {
  13497. // Triangle views
  13498. case BABYLON.Material.TriangleFillMode:
  13499. return this._gl.TRIANGLES;
  13500. case BABYLON.Material.PointFillMode:
  13501. return this._gl.POINTS;
  13502. case BABYLON.Material.WireFrameFillMode:
  13503. return this._gl.LINES;
  13504. // Draw modes
  13505. case BABYLON.Material.PointListDrawMode:
  13506. return this._gl.POINTS;
  13507. case BABYLON.Material.LineListDrawMode:
  13508. return this._gl.LINES;
  13509. case BABYLON.Material.LineLoopDrawMode:
  13510. return this._gl.LINE_LOOP;
  13511. case BABYLON.Material.LineStripDrawMode:
  13512. return this._gl.LINE_STRIP;
  13513. case BABYLON.Material.TriangleStripDrawMode:
  13514. return this._gl.TRIANGLE_STRIP;
  13515. case BABYLON.Material.TriangleFanDrawMode:
  13516. return this._gl.TRIANGLE_FAN;
  13517. default:
  13518. return this._gl.TRIANGLES;
  13519. }
  13520. };
  13521. // Shaders
  13522. /** @hidden */
  13523. Engine.prototype._releaseEffect = function (effect) {
  13524. if (this._compiledEffects[effect._key]) {
  13525. delete this._compiledEffects[effect._key];
  13526. this._deleteProgram(effect.getProgram());
  13527. }
  13528. };
  13529. /** @hidden */
  13530. Engine.prototype._deleteProgram = function (program) {
  13531. if (program) {
  13532. program.__SPECTOR_rebuildProgram = null;
  13533. if (program.transformFeedback) {
  13534. this.deleteTransformFeedback(program.transformFeedback);
  13535. program.transformFeedback = null;
  13536. }
  13537. this._gl.deleteProgram(program);
  13538. }
  13539. };
  13540. /**
  13541. * Create a new effect (used to store vertex/fragment shaders)
  13542. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13543. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13544. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13545. * @param samplers defines an array of string used to represent textures
  13546. * @param defines defines the string containing the defines to use to compile the shaders
  13547. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13548. * @param onCompiled defines a function to call when the effect creation is successful
  13549. * @param onError defines a function to call when the effect creation has failed
  13550. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13551. * @returns the new Effect
  13552. */
  13553. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13554. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13555. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13556. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13557. if (this._compiledEffects[name]) {
  13558. var compiledEffect = this._compiledEffects[name];
  13559. if (onCompiled && compiledEffect.isReady()) {
  13560. onCompiled(compiledEffect);
  13561. }
  13562. return compiledEffect;
  13563. }
  13564. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13565. effect._key = name;
  13566. this._compiledEffects[name] = effect;
  13567. return effect;
  13568. };
  13569. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13570. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13571. };
  13572. ;
  13573. Engine.prototype._compileRawShader = function (source, type) {
  13574. var gl = this._gl;
  13575. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13576. gl.shaderSource(shader, source);
  13577. gl.compileShader(shader);
  13578. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13579. var log = gl.getShaderInfoLog(shader);
  13580. if (log) {
  13581. throw new Error(log);
  13582. }
  13583. }
  13584. if (!shader) {
  13585. throw new Error("Something went wrong while compile the shader.");
  13586. }
  13587. return shader;
  13588. };
  13589. ;
  13590. /**
  13591. * Directly creates a webGL program
  13592. * @param vertexCode defines the vertex shader code to use
  13593. * @param fragmentCode defines the fragment shader code to use
  13594. * @param context defines the webGL context to use (if not set, the current one will be used)
  13595. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13596. * @returns the new webGL program
  13597. */
  13598. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13599. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13600. context = context || this._gl;
  13601. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13602. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13603. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13604. };
  13605. /**
  13606. * Creates a webGL program
  13607. * @param vertexCode defines the vertex shader code to use
  13608. * @param fragmentCode defines the fragment shader code to use
  13609. * @param defines defines the string containing the defines to use to compile the shaders
  13610. * @param context defines the webGL context to use (if not set, the current one will be used)
  13611. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13612. * @returns the new webGL program
  13613. */
  13614. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13615. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13616. context = context || this._gl;
  13617. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13618. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13619. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13620. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13621. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13622. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13623. return program;
  13624. };
  13625. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13626. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13627. var shaderProgram = context.createProgram();
  13628. if (!shaderProgram) {
  13629. throw new Error("Unable to create program");
  13630. }
  13631. context.attachShader(shaderProgram, vertexShader);
  13632. context.attachShader(shaderProgram, fragmentShader);
  13633. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13634. var transformFeedback = this.createTransformFeedback();
  13635. this.bindTransformFeedback(transformFeedback);
  13636. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13637. shaderProgram.transformFeedback = transformFeedback;
  13638. }
  13639. context.linkProgram(shaderProgram);
  13640. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13641. this.bindTransformFeedback(null);
  13642. }
  13643. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13644. if (!linked) {
  13645. var error = context.getProgramInfoLog(shaderProgram);
  13646. if (error) {
  13647. throw new Error(error);
  13648. }
  13649. }
  13650. if (this.validateShaderPrograms) {
  13651. context.validateProgram(shaderProgram);
  13652. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13653. if (!validated) {
  13654. var error = context.getProgramInfoLog(shaderProgram);
  13655. if (error) {
  13656. throw new Error(error);
  13657. }
  13658. }
  13659. }
  13660. context.deleteShader(vertexShader);
  13661. context.deleteShader(fragmentShader);
  13662. return shaderProgram;
  13663. };
  13664. /**
  13665. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13666. * @param shaderProgram defines the webGL program to use
  13667. * @param uniformsNames defines the list of uniform names
  13668. * @returns an array of webGL uniform locations
  13669. */
  13670. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13671. var results = new Array();
  13672. for (var index = 0; index < uniformsNames.length; index++) {
  13673. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13674. }
  13675. return results;
  13676. };
  13677. /**
  13678. * Gets the lsit of active attributes for a given webGL program
  13679. * @param shaderProgram defines the webGL program to use
  13680. * @param attributesNames defines the list of attribute names to get
  13681. * @returns an array of indices indicating the offset of each attribute
  13682. */
  13683. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13684. var results = [];
  13685. for (var index = 0; index < attributesNames.length; index++) {
  13686. try {
  13687. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13688. }
  13689. catch (e) {
  13690. results.push(-1);
  13691. }
  13692. }
  13693. return results;
  13694. };
  13695. /**
  13696. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13697. * @param effect defines the effect to activate
  13698. */
  13699. Engine.prototype.enableEffect = function (effect) {
  13700. if (!effect) {
  13701. return;
  13702. }
  13703. // Use program
  13704. this.bindSamplers(effect);
  13705. this._currentEffect = effect;
  13706. if (effect.onBind) {
  13707. effect.onBind(effect);
  13708. }
  13709. effect.onBindObservable.notifyObservers(effect);
  13710. };
  13711. /**
  13712. * Set the value of an uniform to an array of int32
  13713. * @param uniform defines the webGL uniform location where to store the value
  13714. * @param array defines the array of int32 to store
  13715. */
  13716. Engine.prototype.setIntArray = function (uniform, array) {
  13717. if (!uniform)
  13718. return;
  13719. this._gl.uniform1iv(uniform, array);
  13720. };
  13721. /**
  13722. * Set the value of an uniform to an array of int32 (stored as vec2)
  13723. * @param uniform defines the webGL uniform location where to store the value
  13724. * @param array defines the array of int32 to store
  13725. */
  13726. Engine.prototype.setIntArray2 = function (uniform, array) {
  13727. if (!uniform || array.length % 2 !== 0)
  13728. return;
  13729. this._gl.uniform2iv(uniform, array);
  13730. };
  13731. /**
  13732. * Set the value of an uniform to an array of int32 (stored as vec3)
  13733. * @param uniform defines the webGL uniform location where to store the value
  13734. * @param array defines the array of int32 to store
  13735. */
  13736. Engine.prototype.setIntArray3 = function (uniform, array) {
  13737. if (!uniform || array.length % 3 !== 0)
  13738. return;
  13739. this._gl.uniform3iv(uniform, array);
  13740. };
  13741. /**
  13742. * Set the value of an uniform to an array of int32 (stored as vec4)
  13743. * @param uniform defines the webGL uniform location where to store the value
  13744. * @param array defines the array of int32 to store
  13745. */
  13746. Engine.prototype.setIntArray4 = function (uniform, array) {
  13747. if (!uniform || array.length % 4 !== 0)
  13748. return;
  13749. this._gl.uniform4iv(uniform, array);
  13750. };
  13751. /**
  13752. * Set the value of an uniform to an array of float32
  13753. * @param uniform defines the webGL uniform location where to store the value
  13754. * @param array defines the array of float32 to store
  13755. */
  13756. Engine.prototype.setFloatArray = function (uniform, array) {
  13757. if (!uniform)
  13758. return;
  13759. this._gl.uniform1fv(uniform, array);
  13760. };
  13761. /**
  13762. * Set the value of an uniform to an array of float32 (stored as vec2)
  13763. * @param uniform defines the webGL uniform location where to store the value
  13764. * @param array defines the array of float32 to store
  13765. */
  13766. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13767. if (!uniform || array.length % 2 !== 0)
  13768. return;
  13769. this._gl.uniform2fv(uniform, array);
  13770. };
  13771. /**
  13772. * Set the value of an uniform to an array of float32 (stored as vec3)
  13773. * @param uniform defines the webGL uniform location where to store the value
  13774. * @param array defines the array of float32 to store
  13775. */
  13776. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13777. if (!uniform || array.length % 3 !== 0)
  13778. return;
  13779. this._gl.uniform3fv(uniform, array);
  13780. };
  13781. /**
  13782. * Set the value of an uniform to an array of float32 (stored as vec4)
  13783. * @param uniform defines the webGL uniform location where to store the value
  13784. * @param array defines the array of float32 to store
  13785. */
  13786. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13787. if (!uniform || array.length % 4 !== 0)
  13788. return;
  13789. this._gl.uniform4fv(uniform, array);
  13790. };
  13791. /**
  13792. * Set the value of an uniform to an array of number
  13793. * @param uniform defines the webGL uniform location where to store the value
  13794. * @param array defines the array of number to store
  13795. */
  13796. Engine.prototype.setArray = function (uniform, array) {
  13797. if (!uniform)
  13798. return;
  13799. this._gl.uniform1fv(uniform, array);
  13800. };
  13801. /**
  13802. * Set the value of an uniform to an array of number (stored as vec2)
  13803. * @param uniform defines the webGL uniform location where to store the value
  13804. * @param array defines the array of number to store
  13805. */
  13806. Engine.prototype.setArray2 = function (uniform, array) {
  13807. if (!uniform || array.length % 2 !== 0)
  13808. return;
  13809. this._gl.uniform2fv(uniform, array);
  13810. };
  13811. /**
  13812. * Set the value of an uniform to an array of number (stored as vec3)
  13813. * @param uniform defines the webGL uniform location where to store the value
  13814. * @param array defines the array of number to store
  13815. */
  13816. Engine.prototype.setArray3 = function (uniform, array) {
  13817. if (!uniform || array.length % 3 !== 0)
  13818. return;
  13819. this._gl.uniform3fv(uniform, array);
  13820. };
  13821. /**
  13822. * Set the value of an uniform to an array of number (stored as vec4)
  13823. * @param uniform defines the webGL uniform location where to store the value
  13824. * @param array defines the array of number to store
  13825. */
  13826. Engine.prototype.setArray4 = function (uniform, array) {
  13827. if (!uniform || array.length % 4 !== 0)
  13828. return;
  13829. this._gl.uniform4fv(uniform, array);
  13830. };
  13831. /**
  13832. * Set the value of an uniform to an array of float32 (stored as matrices)
  13833. * @param uniform defines the webGL uniform location where to store the value
  13834. * @param matrices defines the array of float32 to store
  13835. */
  13836. Engine.prototype.setMatrices = function (uniform, matrices) {
  13837. if (!uniform)
  13838. return;
  13839. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13840. };
  13841. /**
  13842. * Set the value of an uniform to a matrix
  13843. * @param uniform defines the webGL uniform location where to store the value
  13844. * @param matrix defines the matrix to store
  13845. */
  13846. Engine.prototype.setMatrix = function (uniform, matrix) {
  13847. if (!uniform)
  13848. return;
  13849. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13850. };
  13851. /**
  13852. * Set the value of an uniform to a matrix (3x3)
  13853. * @param uniform defines the webGL uniform location where to store the value
  13854. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13855. */
  13856. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13857. if (!uniform)
  13858. return;
  13859. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13860. };
  13861. /**
  13862. * Set the value of an uniform to a matrix (2x2)
  13863. * @param uniform defines the webGL uniform location where to store the value
  13864. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13865. */
  13866. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13867. if (!uniform)
  13868. return;
  13869. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13870. };
  13871. /**
  13872. * Set the value of an uniform to a number (int)
  13873. * @param uniform defines the webGL uniform location where to store the value
  13874. * @param value defines the int number to store
  13875. */
  13876. Engine.prototype.setInt = function (uniform, value) {
  13877. if (!uniform)
  13878. return;
  13879. this._gl.uniform1i(uniform, value);
  13880. };
  13881. /**
  13882. * Set the value of an uniform to a number (float)
  13883. * @param uniform defines the webGL uniform location where to store the value
  13884. * @param value defines the float number to store
  13885. */
  13886. Engine.prototype.setFloat = function (uniform, value) {
  13887. if (!uniform)
  13888. return;
  13889. this._gl.uniform1f(uniform, value);
  13890. };
  13891. /**
  13892. * Set the value of an uniform to a vec2
  13893. * @param uniform defines the webGL uniform location where to store the value
  13894. * @param x defines the 1st component of the value
  13895. * @param y defines the 2nd component of the value
  13896. */
  13897. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13898. if (!uniform)
  13899. return;
  13900. this._gl.uniform2f(uniform, x, y);
  13901. };
  13902. /**
  13903. * Set the value of an uniform to a vec3
  13904. * @param uniform defines the webGL uniform location where to store the value
  13905. * @param x defines the 1st component of the value
  13906. * @param y defines the 2nd component of the value
  13907. * @param z defines the 3rd component of the value
  13908. */
  13909. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13910. if (!uniform)
  13911. return;
  13912. this._gl.uniform3f(uniform, x, y, z);
  13913. };
  13914. /**
  13915. * Set the value of an uniform to a boolean
  13916. * @param uniform defines the webGL uniform location where to store the value
  13917. * @param bool defines the boolean to store
  13918. */
  13919. Engine.prototype.setBool = function (uniform, bool) {
  13920. if (!uniform)
  13921. return;
  13922. this._gl.uniform1i(uniform, bool);
  13923. };
  13924. /**
  13925. * Set the value of an uniform to a vec4
  13926. * @param uniform defines the webGL uniform location where to store the value
  13927. * @param x defines the 1st component of the value
  13928. * @param y defines the 2nd component of the value
  13929. * @param z defines the 3rd component of the value
  13930. * @param w defines the 4th component of the value
  13931. */
  13932. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13933. if (!uniform)
  13934. return;
  13935. this._gl.uniform4f(uniform, x, y, z, w);
  13936. };
  13937. /**
  13938. * Set the value of an uniform to a Color3
  13939. * @param uniform defines the webGL uniform location where to store the value
  13940. * @param color3 defines the color to store
  13941. */
  13942. Engine.prototype.setColor3 = function (uniform, color3) {
  13943. if (!uniform)
  13944. return;
  13945. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13946. };
  13947. /**
  13948. * Set the value of an uniform to a Color3 and an alpha value
  13949. * @param uniform defines the webGL uniform location where to store the value
  13950. * @param color3 defines the color to store
  13951. * @param alpha defines the alpha component to store
  13952. */
  13953. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13954. if (!uniform)
  13955. return;
  13956. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13957. };
  13958. /**
  13959. * Sets a Color4 on a uniform variable
  13960. * @param uniform defines the uniform location
  13961. * @param color4 defines the value to be set
  13962. */
  13963. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13964. if (!uniform)
  13965. return;
  13966. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13967. };
  13968. // States
  13969. /**
  13970. * Set various states to the webGL context
  13971. * @param culling defines backface culling state
  13972. * @param zOffset defines the value to apply to zOffset (0 by default)
  13973. * @param force defines if states must be applied even if cache is up to date
  13974. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  13975. */
  13976. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13977. if (zOffset === void 0) { zOffset = 0; }
  13978. if (reverseSide === void 0) { reverseSide = false; }
  13979. // Culling
  13980. if (this._depthCullingState.cull !== culling || force) {
  13981. this._depthCullingState.cull = culling;
  13982. }
  13983. // Cull face
  13984. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13985. if (this._depthCullingState.cullFace !== cullFace || force) {
  13986. this._depthCullingState.cullFace = cullFace;
  13987. }
  13988. // Z offset
  13989. this.setZOffset(zOffset);
  13990. // Front face
  13991. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13992. if (this._depthCullingState.frontFace !== frontFace || force) {
  13993. this._depthCullingState.frontFace = frontFace;
  13994. }
  13995. };
  13996. /**
  13997. * Set the z offset to apply to current rendering
  13998. * @param value defines the offset to apply
  13999. */
  14000. Engine.prototype.setZOffset = function (value) {
  14001. this._depthCullingState.zOffset = value;
  14002. };
  14003. /**
  14004. * Gets the current value of the zOffset
  14005. * @returns the current zOffset state
  14006. */
  14007. Engine.prototype.getZOffset = function () {
  14008. return this._depthCullingState.zOffset;
  14009. };
  14010. /**
  14011. * Enable or disable depth buffering
  14012. * @param enable defines the state to set
  14013. */
  14014. Engine.prototype.setDepthBuffer = function (enable) {
  14015. this._depthCullingState.depthTest = enable;
  14016. };
  14017. /**
  14018. * Gets a boolean indicating if depth writing is enabled
  14019. * @returns the current depth writing state
  14020. */
  14021. Engine.prototype.getDepthWrite = function () {
  14022. return this._depthCullingState.depthMask;
  14023. };
  14024. /**
  14025. * Enable or disable depth writing
  14026. * @param enable defines the state to set
  14027. */
  14028. Engine.prototype.setDepthWrite = function (enable) {
  14029. this._depthCullingState.depthMask = enable;
  14030. };
  14031. /**
  14032. * Enable or disable color writing
  14033. * @param enable defines the state to set
  14034. */
  14035. Engine.prototype.setColorWrite = function (enable) {
  14036. this._gl.colorMask(enable, enable, enable, enable);
  14037. this._colorWrite = enable;
  14038. };
  14039. /**
  14040. * Gets a boolean indicating if color writing is enabled
  14041. * @returns the current color writing state
  14042. */
  14043. Engine.prototype.getColorWrite = function () {
  14044. return this._colorWrite;
  14045. };
  14046. /**
  14047. * Sets alpha constants used by some alpha blending modes
  14048. * @param r defines the red component
  14049. * @param g defines the green component
  14050. * @param b defines the blue component
  14051. * @param a defines the alpha component
  14052. */
  14053. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14054. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14055. };
  14056. /**
  14057. * Sets the current alpha mode
  14058. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14059. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14060. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14061. */
  14062. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14063. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14064. if (this._alphaMode === mode) {
  14065. return;
  14066. }
  14067. switch (mode) {
  14068. case Engine.ALPHA_DISABLE:
  14069. this._alphaState.alphaBlend = false;
  14070. break;
  14071. case Engine.ALPHA_PREMULTIPLIED:
  14072. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14073. this._alphaState.alphaBlend = true;
  14074. break;
  14075. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14076. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14077. this._alphaState.alphaBlend = true;
  14078. break;
  14079. case Engine.ALPHA_COMBINE:
  14080. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14081. this._alphaState.alphaBlend = true;
  14082. break;
  14083. case Engine.ALPHA_ONEONE:
  14084. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14085. this._alphaState.alphaBlend = true;
  14086. break;
  14087. case Engine.ALPHA_ADD:
  14088. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14089. this._alphaState.alphaBlend = true;
  14090. break;
  14091. case Engine.ALPHA_SUBTRACT:
  14092. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14093. this._alphaState.alphaBlend = true;
  14094. break;
  14095. case Engine.ALPHA_MULTIPLY:
  14096. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14097. this._alphaState.alphaBlend = true;
  14098. break;
  14099. case Engine.ALPHA_MAXIMIZED:
  14100. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14101. this._alphaState.alphaBlend = true;
  14102. break;
  14103. case Engine.ALPHA_INTERPOLATE:
  14104. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14105. this._alphaState.alphaBlend = true;
  14106. break;
  14107. case Engine.ALPHA_SCREENMODE:
  14108. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14109. this._alphaState.alphaBlend = true;
  14110. break;
  14111. }
  14112. if (!noDepthWriteChange) {
  14113. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14114. }
  14115. this._alphaMode = mode;
  14116. };
  14117. /**
  14118. * Gets the current alpha mode
  14119. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14120. * @returns the current alpha mode
  14121. */
  14122. Engine.prototype.getAlphaMode = function () {
  14123. return this._alphaMode;
  14124. };
  14125. // Textures
  14126. /**
  14127. * Clears the list of texture accessible through engine.
  14128. * This can help preventing texture load conflict due to name collision.
  14129. */
  14130. Engine.prototype.clearInternalTexturesCache = function () {
  14131. this._internalTexturesCache = [];
  14132. };
  14133. /**
  14134. * Force the entire cache to be cleared
  14135. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14136. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14137. */
  14138. Engine.prototype.wipeCaches = function (bruteForce) {
  14139. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14140. return;
  14141. }
  14142. this._currentEffect = null;
  14143. this._unpackFlipYCached = null;
  14144. this._viewportCached.x = 0;
  14145. this._viewportCached.y = 0;
  14146. this._viewportCached.z = 0;
  14147. this._viewportCached.w = 0;
  14148. if (bruteForce) {
  14149. this.resetTextureCache();
  14150. this._currentProgram = null;
  14151. this._stencilState.reset();
  14152. this._depthCullingState.reset();
  14153. this.setDepthFunctionToLessOrEqual();
  14154. this._alphaState.reset();
  14155. }
  14156. this._resetVertexBufferBinding();
  14157. this._cachedIndexBuffer = null;
  14158. this._cachedEffectForVertexBuffers = null;
  14159. this._unbindVertexArrayObject();
  14160. this.bindIndexBuffer(null);
  14161. };
  14162. /**
  14163. * Set the compressed texture format to use, based on the formats you have, and the formats
  14164. * supported by the hardware / browser.
  14165. *
  14166. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14167. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14168. * to API arguments needed to compressed textures. This puts the burden on the container
  14169. * generator to house the arcane code for determining these for current & future formats.
  14170. *
  14171. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14172. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14173. *
  14174. * Note: The result of this call is not taken into account when a texture is base64.
  14175. *
  14176. * @param formatsAvailable defines the list of those format families you have created
  14177. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14178. *
  14179. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14180. * @returns The extension selected.
  14181. */
  14182. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14183. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14184. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14185. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14186. return this._textureFormatInUse = this._texturesSupported[i];
  14187. }
  14188. }
  14189. }
  14190. // actively set format to nothing, to allow this to be called more than once
  14191. // and possibly fail the 2nd time
  14192. this._textureFormatInUse = null;
  14193. return null;
  14194. };
  14195. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14196. var gl = this._gl;
  14197. var magFilter = gl.NEAREST;
  14198. var minFilter = gl.NEAREST;
  14199. switch (samplingMode) {
  14200. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14201. magFilter = gl.LINEAR;
  14202. if (generateMipMaps) {
  14203. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14204. }
  14205. else {
  14206. minFilter = gl.LINEAR;
  14207. }
  14208. break;
  14209. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14210. magFilter = gl.LINEAR;
  14211. if (generateMipMaps) {
  14212. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14213. }
  14214. else {
  14215. minFilter = gl.LINEAR;
  14216. }
  14217. break;
  14218. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14219. magFilter = gl.NEAREST;
  14220. if (generateMipMaps) {
  14221. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14222. }
  14223. else {
  14224. minFilter = gl.NEAREST;
  14225. }
  14226. break;
  14227. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14228. magFilter = gl.NEAREST;
  14229. if (generateMipMaps) {
  14230. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14231. }
  14232. else {
  14233. minFilter = gl.NEAREST;
  14234. }
  14235. break;
  14236. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14237. magFilter = gl.NEAREST;
  14238. if (generateMipMaps) {
  14239. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14240. }
  14241. else {
  14242. minFilter = gl.LINEAR;
  14243. }
  14244. break;
  14245. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14246. magFilter = gl.NEAREST;
  14247. if (generateMipMaps) {
  14248. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14249. }
  14250. else {
  14251. minFilter = gl.LINEAR;
  14252. }
  14253. break;
  14254. case Engine.TEXTURE_NEAREST_LINEAR:
  14255. magFilter = gl.NEAREST;
  14256. minFilter = gl.LINEAR;
  14257. break;
  14258. case Engine.TEXTURE_NEAREST_NEAREST:
  14259. magFilter = gl.NEAREST;
  14260. minFilter = gl.NEAREST;
  14261. break;
  14262. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14263. magFilter = gl.LINEAR;
  14264. if (generateMipMaps) {
  14265. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14266. }
  14267. else {
  14268. minFilter = gl.NEAREST;
  14269. }
  14270. break;
  14271. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14272. magFilter = gl.LINEAR;
  14273. if (generateMipMaps) {
  14274. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14275. }
  14276. else {
  14277. minFilter = gl.NEAREST;
  14278. }
  14279. break;
  14280. case Engine.TEXTURE_LINEAR_LINEAR:
  14281. magFilter = gl.LINEAR;
  14282. minFilter = gl.LINEAR;
  14283. break;
  14284. case Engine.TEXTURE_LINEAR_NEAREST:
  14285. magFilter = gl.LINEAR;
  14286. minFilter = gl.NEAREST;
  14287. break;
  14288. }
  14289. return {
  14290. min: minFilter,
  14291. mag: magFilter
  14292. };
  14293. };
  14294. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14295. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14296. var img;
  14297. var onload = function () {
  14298. loadedImages[index] = img;
  14299. loadedImages._internalCount++;
  14300. if (scene) {
  14301. scene._removePendingData(img);
  14302. }
  14303. if (loadedImages._internalCount === 6) {
  14304. onfinish(loadedImages);
  14305. }
  14306. };
  14307. var onerror = function (message, exception) {
  14308. if (scene) {
  14309. scene._removePendingData(img);
  14310. }
  14311. if (onErrorCallBack) {
  14312. onErrorCallBack(message, exception);
  14313. }
  14314. };
  14315. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14316. if (scene) {
  14317. scene._addPendingData(img);
  14318. }
  14319. };
  14320. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14321. if (onError === void 0) { onError = null; }
  14322. var loadedImages = [];
  14323. loadedImages._internalCount = 0;
  14324. for (var index = 0; index < 6; index++) {
  14325. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14326. }
  14327. };
  14328. ;
  14329. /** @hidden */
  14330. Engine.prototype._createTexture = function () {
  14331. var texture = this._gl.createTexture();
  14332. if (!texture) {
  14333. throw new Error("Unable to create texture");
  14334. }
  14335. return texture;
  14336. };
  14337. /**
  14338. * Usually called from BABYLON.Texture.ts.
  14339. * Passed information to create a WebGLTexture
  14340. * @param urlArg defines a value which contains one of the following:
  14341. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14342. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14343. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14344. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14345. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14346. * @param scene needed for loading to the correct scene
  14347. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14348. * @param onLoad optional callback to be called upon successful completion
  14349. * @param onError optional callback to be called upon failure
  14350. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14351. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14352. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14353. * @param forcedExtension defines the extension to use to pick the right loader
  14354. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14355. */
  14356. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14357. var _this = this;
  14358. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14359. if (onLoad === void 0) { onLoad = null; }
  14360. if (onError === void 0) { onError = null; }
  14361. if (buffer === void 0) { buffer = null; }
  14362. if (fallback === void 0) { fallback = null; }
  14363. if (format === void 0) { format = null; }
  14364. if (forcedExtension === void 0) { forcedExtension = null; }
  14365. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14366. var fromData = url.substr(0, 5) === "data:";
  14367. var fromBlob = url.substr(0, 5) === "blob:";
  14368. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14369. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14370. // establish the file extension, if possible
  14371. var lastDot = url.lastIndexOf('.');
  14372. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14373. var loader = null;
  14374. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14375. var availableLoader = _a[_i];
  14376. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14377. loader = availableLoader;
  14378. break;
  14379. }
  14380. }
  14381. if (loader) {
  14382. url = loader.transformUrl(url, this._textureFormatInUse);
  14383. }
  14384. if (scene) {
  14385. scene._addPendingData(texture);
  14386. }
  14387. texture.url = url;
  14388. texture.generateMipMaps = !noMipmap;
  14389. texture.samplingMode = samplingMode;
  14390. texture.invertY = invertY;
  14391. if (!this._doNotHandleContextLost) {
  14392. // Keep a link to the buffer only if we plan to handle context lost
  14393. texture._buffer = buffer;
  14394. }
  14395. var onLoadObserver = null;
  14396. if (onLoad && !fallback) {
  14397. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14398. }
  14399. if (!fallback)
  14400. this._internalTexturesCache.push(texture);
  14401. var onInternalError = function (message, exception) {
  14402. if (scene) {
  14403. scene._removePendingData(texture);
  14404. }
  14405. var customFallback = false;
  14406. if (loader) {
  14407. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14408. if (fallbackUrl) {
  14409. // Add Back
  14410. customFallback = true;
  14411. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14412. }
  14413. }
  14414. if (!customFallback) {
  14415. if (onLoadObserver) {
  14416. texture.onLoadedObservable.remove(onLoadObserver);
  14417. }
  14418. if (BABYLON.Tools.UseFallbackTexture) {
  14419. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14420. }
  14421. }
  14422. if (onError) {
  14423. onError(message || "Unknown error", exception);
  14424. }
  14425. };
  14426. // processing for non-image formats
  14427. if (loader) {
  14428. var callback = function (data) {
  14429. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14430. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14431. done();
  14432. return false;
  14433. }, samplingMode);
  14434. });
  14435. };
  14436. if (!buffer) {
  14437. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14438. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14439. });
  14440. }
  14441. else {
  14442. callback(buffer);
  14443. }
  14444. }
  14445. else {
  14446. var onload = function (img) {
  14447. if (fromBlob && !_this._doNotHandleContextLost) {
  14448. // We need to store the image if we need to rebuild the texture
  14449. // in case of a webgl context lost
  14450. texture._buffer = img;
  14451. }
  14452. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14453. var gl = _this._gl;
  14454. var isPot = (img.width === potWidth && img.height === potHeight);
  14455. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14456. if (isPot) {
  14457. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14458. return false;
  14459. }
  14460. var maxTextureSize = _this._caps.maxTextureSize;
  14461. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14462. _this._prepareWorkingCanvas();
  14463. if (!_this._workingCanvas || !_this._workingContext) {
  14464. return false;
  14465. }
  14466. _this._workingCanvas.width = potWidth;
  14467. _this._workingCanvas.height = potHeight;
  14468. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14469. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14470. texture.width = potWidth;
  14471. texture.height = potHeight;
  14472. return false;
  14473. }
  14474. else {
  14475. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14476. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14477. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14478. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14479. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14480. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14481. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14482. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14483. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14484. _this._releaseTexture(source_1);
  14485. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14486. continuationCallback();
  14487. });
  14488. }
  14489. return true;
  14490. }, samplingMode);
  14491. };
  14492. if (!fromData || isBase64) {
  14493. if (buffer instanceof HTMLImageElement) {
  14494. onload(buffer);
  14495. }
  14496. else {
  14497. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14498. }
  14499. }
  14500. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14501. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14502. }
  14503. else {
  14504. onload(buffer);
  14505. }
  14506. }
  14507. return texture;
  14508. };
  14509. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14510. var _this = this;
  14511. var rtt = this.createRenderTargetTexture({
  14512. width: destination.width,
  14513. height: destination.height,
  14514. }, {
  14515. generateMipMaps: false,
  14516. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14517. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14518. generateDepthBuffer: false,
  14519. generateStencilBuffer: false
  14520. });
  14521. if (!this._rescalePostProcess) {
  14522. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14523. }
  14524. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14525. _this._rescalePostProcess.onApply = function (effect) {
  14526. effect._bindTexture("textureSampler", source);
  14527. };
  14528. var hostingScene = scene;
  14529. if (!hostingScene) {
  14530. hostingScene = _this.scenes[_this.scenes.length - 1];
  14531. }
  14532. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14533. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14534. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14535. _this.unBindFramebuffer(rtt);
  14536. _this._releaseTexture(rtt);
  14537. if (onComplete) {
  14538. onComplete();
  14539. }
  14540. });
  14541. };
  14542. /**
  14543. * Update a raw texture
  14544. * @param texture defines the texture to update
  14545. * @param data defines the data to store in the texture
  14546. * @param format defines the format of the data
  14547. * @param invertY defines if data must be stored with Y axis inverted
  14548. * @param compression defines the compression used (null by default)
  14549. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14550. */
  14551. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14552. if (compression === void 0) { compression = null; }
  14553. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14554. if (!texture) {
  14555. return;
  14556. }
  14557. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14558. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14559. // babylon's internalFormat but gl's texImage2D format
  14560. var internalFormat = this._getInternalFormat(format);
  14561. var textureType = this._getWebGLTextureType(type);
  14562. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14563. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14564. if (!this._doNotHandleContextLost) {
  14565. texture._bufferView = data;
  14566. texture.format = format;
  14567. texture.type = type;
  14568. texture.invertY = invertY;
  14569. texture._compression = compression;
  14570. }
  14571. if (texture.width % 4 !== 0) {
  14572. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14573. }
  14574. if (compression && data) {
  14575. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14576. }
  14577. else {
  14578. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14579. }
  14580. if (texture.generateMipMaps) {
  14581. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14582. }
  14583. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14584. // this.resetTextureCache();
  14585. texture.isReady = true;
  14586. };
  14587. /**
  14588. * Creates a raw texture
  14589. * @param data defines the data to store in the texture
  14590. * @param width defines the width of the texture
  14591. * @param height defines the height of the texture
  14592. * @param format defines the format of the data
  14593. * @param generateMipMaps defines if the engine should generate the mip levels
  14594. * @param invertY defines if data must be stored with Y axis inverted
  14595. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14596. * @param compression defines the compression used (null by default)
  14597. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14598. * @returns the raw texture inside an InternalTexture
  14599. */
  14600. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14601. if (compression === void 0) { compression = null; }
  14602. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14603. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14604. texture.baseWidth = width;
  14605. texture.baseHeight = height;
  14606. texture.width = width;
  14607. texture.height = height;
  14608. texture.format = format;
  14609. texture.generateMipMaps = generateMipMaps;
  14610. texture.samplingMode = samplingMode;
  14611. texture.invertY = invertY;
  14612. texture._compression = compression;
  14613. texture.type = type;
  14614. if (!this._doNotHandleContextLost) {
  14615. texture._bufferView = data;
  14616. }
  14617. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14618. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14619. // Filters
  14620. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14621. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14622. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14623. if (generateMipMaps) {
  14624. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14625. }
  14626. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14627. this._internalTexturesCache.push(texture);
  14628. return texture;
  14629. };
  14630. /** @hidden */
  14631. Engine.prototype._unpackFlipY = function (value) {
  14632. if (this._unpackFlipYCached !== value) {
  14633. this._unpackFlipYCached = value;
  14634. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14635. }
  14636. };
  14637. /** @hidden */
  14638. Engine.prototype._getUnpackAlignement = function () {
  14639. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14640. };
  14641. /**
  14642. * Creates a dynamic texture
  14643. * @param width defines the width of the texture
  14644. * @param height defines the height of the texture
  14645. * @param generateMipMaps defines if the engine should generate the mip levels
  14646. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14647. * @returns the dynamic texture inside an InternalTexture
  14648. */
  14649. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14650. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14651. texture.baseWidth = width;
  14652. texture.baseHeight = height;
  14653. if (generateMipMaps) {
  14654. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14655. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14656. }
  14657. // this.resetTextureCache();
  14658. texture.width = width;
  14659. texture.height = height;
  14660. texture.isReady = false;
  14661. texture.generateMipMaps = generateMipMaps;
  14662. texture.samplingMode = samplingMode;
  14663. this.updateTextureSamplingMode(samplingMode, texture);
  14664. this._internalTexturesCache.push(texture);
  14665. return texture;
  14666. };
  14667. /**
  14668. * Update the sampling mode of a given texture
  14669. * @param samplingMode defines the required sampling mode
  14670. * @param texture defines the texture to update
  14671. */
  14672. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14673. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14674. if (texture.isCube) {
  14675. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14676. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14677. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14678. }
  14679. else if (texture.is3D) {
  14680. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14681. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14682. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14683. }
  14684. else {
  14685. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14686. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14687. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14688. }
  14689. texture.samplingMode = samplingMode;
  14690. };
  14691. /**
  14692. * Update the content of a dynamic texture
  14693. * @param texture defines the texture to update
  14694. * @param canvas defines the canvas containing the source
  14695. * @param invertY defines if data must be stored with Y axis inverted
  14696. * @param premulAlpha defines if alpha is stored as premultiplied
  14697. * @param format defines the format of the data
  14698. */
  14699. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14700. if (premulAlpha === void 0) { premulAlpha = false; }
  14701. if (!texture) {
  14702. return;
  14703. }
  14704. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14705. this._unpackFlipY(invertY);
  14706. if (premulAlpha) {
  14707. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14708. }
  14709. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14710. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14711. if (texture.generateMipMaps) {
  14712. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14713. }
  14714. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14715. if (premulAlpha) {
  14716. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14717. }
  14718. texture.isReady = true;
  14719. };
  14720. /**
  14721. * Update a video texture
  14722. * @param texture defines the texture to update
  14723. * @param video defines the video element to use
  14724. * @param invertY defines if data must be stored with Y axis inverted
  14725. */
  14726. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14727. if (!texture || texture._isDisabled) {
  14728. return;
  14729. }
  14730. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14731. this._unpackFlipY(!invertY); // Video are upside down by default
  14732. try {
  14733. // Testing video texture support
  14734. if (this._videoTextureSupported === undefined) {
  14735. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14736. if (this._gl.getError() !== 0) {
  14737. this._videoTextureSupported = false;
  14738. }
  14739. else {
  14740. this._videoTextureSupported = true;
  14741. }
  14742. }
  14743. // Copy video through the current working canvas if video texture is not supported
  14744. if (!this._videoTextureSupported) {
  14745. if (!texture._workingCanvas) {
  14746. texture._workingCanvas = document.createElement("canvas");
  14747. var context = texture._workingCanvas.getContext("2d");
  14748. if (!context) {
  14749. throw new Error("Unable to get 2d context");
  14750. }
  14751. texture._workingContext = context;
  14752. texture._workingCanvas.width = texture.width;
  14753. texture._workingCanvas.height = texture.height;
  14754. }
  14755. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14756. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14757. }
  14758. else {
  14759. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14760. }
  14761. if (texture.generateMipMaps) {
  14762. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14763. }
  14764. if (!wasPreviouslyBound) {
  14765. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14766. }
  14767. // this.resetTextureCache();
  14768. texture.isReady = true;
  14769. }
  14770. catch (ex) {
  14771. // Something unexpected
  14772. // Let's disable the texture
  14773. texture._isDisabled = true;
  14774. }
  14775. };
  14776. /**
  14777. * Updates a depth texture Comparison Mode and Function.
  14778. * If the comparison Function is equal to 0, the mode will be set to none.
  14779. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14780. * @param texture The texture to set the comparison function for
  14781. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14782. */
  14783. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14784. if (this.webGLVersion === 1) {
  14785. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14786. return;
  14787. }
  14788. var gl = this._gl;
  14789. if (texture.isCube) {
  14790. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14791. if (comparisonFunction === 0) {
  14792. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14793. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14794. }
  14795. else {
  14796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14798. }
  14799. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14800. }
  14801. else {
  14802. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14803. if (comparisonFunction === 0) {
  14804. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14805. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14806. }
  14807. else {
  14808. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14809. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14810. }
  14811. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14812. }
  14813. texture._comparisonFunction = comparisonFunction;
  14814. };
  14815. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14816. var width = size.width || size;
  14817. var height = size.height || size;
  14818. internalTexture.baseWidth = width;
  14819. internalTexture.baseHeight = height;
  14820. internalTexture.width = width;
  14821. internalTexture.height = height;
  14822. internalTexture.isReady = true;
  14823. internalTexture.samples = 1;
  14824. internalTexture.generateMipMaps = false;
  14825. internalTexture._generateDepthBuffer = true;
  14826. internalTexture._generateStencilBuffer = generateStencil;
  14827. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14828. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14829. internalTexture._comparisonFunction = comparisonFunction;
  14830. var gl = this._gl;
  14831. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14832. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14833. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14834. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14835. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14836. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14837. if (comparisonFunction === 0) {
  14838. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14839. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14840. }
  14841. else {
  14842. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14843. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14844. }
  14845. };
  14846. /**
  14847. * Creates a depth stencil texture.
  14848. * This is only available in WebGL 2 or with the depth texture extension available.
  14849. * @param size The size of face edge in the texture.
  14850. * @param options The options defining the texture.
  14851. * @returns The texture
  14852. */
  14853. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14854. if (options.isCube) {
  14855. var width = size.width || size;
  14856. return this._createDepthStencilCubeTexture(width, options);
  14857. }
  14858. else {
  14859. return this._createDepthStencilTexture(size, options);
  14860. }
  14861. };
  14862. /**
  14863. * Creates a depth stencil texture.
  14864. * This is only available in WebGL 2 or with the depth texture extension available.
  14865. * @param size The size of face edge in the texture.
  14866. * @param options The options defining the texture.
  14867. * @returns The texture
  14868. */
  14869. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14870. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14871. if (!this._caps.depthTextureExtension) {
  14872. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14873. return internalTexture;
  14874. }
  14875. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14876. var gl = this._gl;
  14877. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14878. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14879. if (this.webGLVersion > 1) {
  14880. if (internalOptions.generateStencil) {
  14881. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14882. }
  14883. else {
  14884. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14885. }
  14886. }
  14887. else {
  14888. if (internalOptions.generateStencil) {
  14889. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14890. }
  14891. else {
  14892. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14893. }
  14894. }
  14895. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14896. return internalTexture;
  14897. };
  14898. /**
  14899. * Creates a depth stencil cube texture.
  14900. * This is only available in WebGL 2.
  14901. * @param size The size of face edge in the cube texture.
  14902. * @param options The options defining the cube texture.
  14903. * @returns The cube texture
  14904. */
  14905. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14906. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14907. internalTexture.isCube = true;
  14908. if (this.webGLVersion === 1) {
  14909. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14910. return internalTexture;
  14911. }
  14912. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14913. var gl = this._gl;
  14914. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14915. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14916. // Create the depth/stencil buffer
  14917. for (var face = 0; face < 6; face++) {
  14918. if (internalOptions.generateStencil) {
  14919. 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);
  14920. }
  14921. else {
  14922. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14923. }
  14924. }
  14925. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14926. return internalTexture;
  14927. };
  14928. /**
  14929. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14930. * @param renderTarget The render target to set the frame buffer for
  14931. */
  14932. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14933. // Create the framebuffer
  14934. var internalTexture = renderTarget.getInternalTexture();
  14935. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14936. return;
  14937. }
  14938. var gl = this._gl;
  14939. var depthStencilTexture = renderTarget.depthStencilTexture;
  14940. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14941. if (depthStencilTexture.isCube) {
  14942. if (depthStencilTexture._generateStencilBuffer) {
  14943. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14944. }
  14945. else {
  14946. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14947. }
  14948. }
  14949. else {
  14950. if (depthStencilTexture._generateStencilBuffer) {
  14951. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14952. }
  14953. else {
  14954. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14955. }
  14956. }
  14957. this.bindUnboundFramebuffer(null);
  14958. };
  14959. /**
  14960. * Creates a new render target texture
  14961. * @param size defines the size of the texture
  14962. * @param options defines the options used to create the texture
  14963. * @returns a new render target texture stored in an InternalTexture
  14964. */
  14965. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14966. var fullOptions = new RenderTargetCreationOptions();
  14967. if (options !== undefined && typeof options === "object") {
  14968. fullOptions.generateMipMaps = options.generateMipMaps;
  14969. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14970. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14971. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14972. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14973. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14974. }
  14975. else {
  14976. fullOptions.generateMipMaps = options;
  14977. fullOptions.generateDepthBuffer = true;
  14978. fullOptions.generateStencilBuffer = false;
  14979. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14980. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  14981. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14982. }
  14983. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14984. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14985. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14986. }
  14987. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14988. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14989. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14990. }
  14991. var gl = this._gl;
  14992. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14993. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14994. var width = size.width || size;
  14995. var height = size.height || size;
  14996. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  14997. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14998. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14999. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15000. }
  15001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15002. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15003. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15004. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15005. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15006. // Create the framebuffer
  15007. var currentFrameBuffer = this._currentFramebuffer;
  15008. var framebuffer = gl.createFramebuffer();
  15009. this.bindUnboundFramebuffer(framebuffer);
  15010. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15011. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15012. if (fullOptions.generateMipMaps) {
  15013. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15014. }
  15015. // Unbind
  15016. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15017. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15018. this.bindUnboundFramebuffer(currentFrameBuffer);
  15019. texture._framebuffer = framebuffer;
  15020. texture.baseWidth = width;
  15021. texture.baseHeight = height;
  15022. texture.width = width;
  15023. texture.height = height;
  15024. texture.isReady = true;
  15025. texture.samples = 1;
  15026. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15027. texture.samplingMode = fullOptions.samplingMode;
  15028. texture.type = fullOptions.type;
  15029. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15030. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15031. // this.resetTextureCache();
  15032. this._internalTexturesCache.push(texture);
  15033. return texture;
  15034. };
  15035. /**
  15036. * Create a multi render target texture
  15037. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15038. * @param size defines the size of the texture
  15039. * @param options defines the creation options
  15040. * @returns the cube texture as an InternalTexture
  15041. */
  15042. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15043. var generateMipMaps = false;
  15044. var generateDepthBuffer = true;
  15045. var generateStencilBuffer = false;
  15046. var generateDepthTexture = false;
  15047. var textureCount = 1;
  15048. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15049. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15050. var types = new Array();
  15051. var samplingModes = new Array();
  15052. if (options !== undefined) {
  15053. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15054. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15055. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15056. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15057. textureCount = options.textureCount || 1;
  15058. if (options.types) {
  15059. types = options.types;
  15060. }
  15061. if (options.samplingModes) {
  15062. samplingModes = options.samplingModes;
  15063. }
  15064. }
  15065. var gl = this._gl;
  15066. // Create the framebuffer
  15067. var framebuffer = gl.createFramebuffer();
  15068. this.bindUnboundFramebuffer(framebuffer);
  15069. var width = size.width || size;
  15070. var height = size.height || size;
  15071. var textures = [];
  15072. var attachments = [];
  15073. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15074. for (var i = 0; i < textureCount; i++) {
  15075. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15076. var type = types[i] || defaultType;
  15077. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15078. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15079. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15080. }
  15081. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15082. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15083. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15084. }
  15085. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15086. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15087. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15088. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15089. }
  15090. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15091. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15092. textures.push(texture);
  15093. attachments.push(attachment);
  15094. gl.activeTexture(gl["TEXTURE" + i]);
  15095. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15096. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15097. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15098. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15100. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15101. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15102. if (generateMipMaps) {
  15103. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15104. }
  15105. // Unbind
  15106. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15107. texture._framebuffer = framebuffer;
  15108. texture._depthStencilBuffer = depthStencilBuffer;
  15109. texture.baseWidth = width;
  15110. texture.baseHeight = height;
  15111. texture.width = width;
  15112. texture.height = height;
  15113. texture.isReady = true;
  15114. texture.samples = 1;
  15115. texture.generateMipMaps = generateMipMaps;
  15116. texture.samplingMode = samplingMode;
  15117. texture.type = type;
  15118. texture._generateDepthBuffer = generateDepthBuffer;
  15119. texture._generateStencilBuffer = generateStencilBuffer;
  15120. texture._attachments = attachments;
  15121. this._internalTexturesCache.push(texture);
  15122. }
  15123. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15124. // Depth texture
  15125. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15126. gl.activeTexture(gl.TEXTURE0);
  15127. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15128. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15129. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15130. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15131. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15132. 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);
  15133. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15134. depthTexture._framebuffer = framebuffer;
  15135. depthTexture.baseWidth = width;
  15136. depthTexture.baseHeight = height;
  15137. depthTexture.width = width;
  15138. depthTexture.height = height;
  15139. depthTexture.isReady = true;
  15140. depthTexture.samples = 1;
  15141. depthTexture.generateMipMaps = generateMipMaps;
  15142. depthTexture.samplingMode = gl.NEAREST;
  15143. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15144. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15145. textures.push(depthTexture);
  15146. this._internalTexturesCache.push(depthTexture);
  15147. }
  15148. gl.drawBuffers(attachments);
  15149. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15150. this.bindUnboundFramebuffer(null);
  15151. this.resetTextureCache();
  15152. return textures;
  15153. };
  15154. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15155. if (samples === void 0) { samples = 1; }
  15156. var depthStencilBuffer = null;
  15157. var gl = this._gl;
  15158. // Create the depth/stencil buffer
  15159. if (generateStencilBuffer) {
  15160. depthStencilBuffer = gl.createRenderbuffer();
  15161. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15162. if (samples > 1) {
  15163. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15164. }
  15165. else {
  15166. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15167. }
  15168. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15169. }
  15170. else if (generateDepthBuffer) {
  15171. depthStencilBuffer = gl.createRenderbuffer();
  15172. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15173. if (samples > 1) {
  15174. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15175. }
  15176. else {
  15177. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15178. }
  15179. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15180. }
  15181. return depthStencilBuffer;
  15182. };
  15183. /**
  15184. * Updates the sample count of a render target texture
  15185. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15186. * @param texture defines the texture to update
  15187. * @param samples defines the sample count to set
  15188. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15189. */
  15190. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15191. if (this.webGLVersion < 2 || !texture) {
  15192. return 1;
  15193. }
  15194. if (texture.samples === samples) {
  15195. return samples;
  15196. }
  15197. var gl = this._gl;
  15198. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15199. // Dispose previous render buffers
  15200. if (texture._depthStencilBuffer) {
  15201. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15202. texture._depthStencilBuffer = null;
  15203. }
  15204. if (texture._MSAAFramebuffer) {
  15205. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15206. texture._MSAAFramebuffer = null;
  15207. }
  15208. if (texture._MSAARenderBuffer) {
  15209. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15210. texture._MSAARenderBuffer = null;
  15211. }
  15212. if (samples > 1) {
  15213. var framebuffer = gl.createFramebuffer();
  15214. if (!framebuffer) {
  15215. throw new Error("Unable to create multi sampled framebuffer");
  15216. }
  15217. texture._MSAAFramebuffer = framebuffer;
  15218. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15219. var colorRenderbuffer = gl.createRenderbuffer();
  15220. if (!colorRenderbuffer) {
  15221. throw new Error("Unable to create multi sampled framebuffer");
  15222. }
  15223. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15224. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15225. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15226. texture._MSAARenderBuffer = colorRenderbuffer;
  15227. }
  15228. else {
  15229. this.bindUnboundFramebuffer(texture._framebuffer);
  15230. }
  15231. texture.samples = samples;
  15232. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15233. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15234. this.bindUnboundFramebuffer(null);
  15235. return samples;
  15236. };
  15237. /**
  15238. * Update the sample count for a given multiple render target texture
  15239. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15240. * @param textures defines the textures to update
  15241. * @param samples defines the sample count to set
  15242. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15243. */
  15244. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15245. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15246. return 1;
  15247. }
  15248. if (textures[0].samples === samples) {
  15249. return samples;
  15250. }
  15251. var gl = this._gl;
  15252. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15253. // Dispose previous render buffers
  15254. if (textures[0]._depthStencilBuffer) {
  15255. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15256. textures[0]._depthStencilBuffer = null;
  15257. }
  15258. if (textures[0]._MSAAFramebuffer) {
  15259. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15260. textures[0]._MSAAFramebuffer = null;
  15261. }
  15262. for (var i = 0; i < textures.length; i++) {
  15263. if (textures[i]._MSAARenderBuffer) {
  15264. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15265. textures[i]._MSAARenderBuffer = null;
  15266. }
  15267. }
  15268. if (samples > 1) {
  15269. var framebuffer = gl.createFramebuffer();
  15270. if (!framebuffer) {
  15271. throw new Error("Unable to create multi sampled framebuffer");
  15272. }
  15273. this.bindUnboundFramebuffer(framebuffer);
  15274. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15275. var attachments = [];
  15276. for (var i = 0; i < textures.length; i++) {
  15277. var texture = textures[i];
  15278. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15279. var colorRenderbuffer = gl.createRenderbuffer();
  15280. if (!colorRenderbuffer) {
  15281. throw new Error("Unable to create multi sampled framebuffer");
  15282. }
  15283. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15284. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15285. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15286. texture._MSAAFramebuffer = framebuffer;
  15287. texture._MSAARenderBuffer = colorRenderbuffer;
  15288. texture.samples = samples;
  15289. texture._depthStencilBuffer = depthStencilBuffer;
  15290. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15291. attachments.push(attachment);
  15292. }
  15293. gl.drawBuffers(attachments);
  15294. }
  15295. else {
  15296. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15297. }
  15298. this.bindUnboundFramebuffer(null);
  15299. return samples;
  15300. };
  15301. /** @hidden */
  15302. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15303. if (faceIndex === void 0) { faceIndex = 0; }
  15304. if (lod === void 0) { lod = 0; }
  15305. var gl = this._gl;
  15306. var target = gl.TEXTURE_2D;
  15307. if (texture.isCube) {
  15308. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15309. }
  15310. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15311. };
  15312. /** @hidden */
  15313. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15314. if (faceIndex === void 0) { faceIndex = 0; }
  15315. if (lod === void 0) { lod = 0; }
  15316. var gl = this._gl;
  15317. var textureType = this._getWebGLTextureType(texture.type);
  15318. var format = this._getInternalFormat(texture.format);
  15319. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15320. this._unpackFlipY(texture.invertY);
  15321. var target = gl.TEXTURE_2D;
  15322. if (texture.isCube) {
  15323. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15324. }
  15325. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15326. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15327. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15328. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15329. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15330. };
  15331. /** @hidden */
  15332. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15333. if (faceIndex === void 0) { faceIndex = 0; }
  15334. if (lod === void 0) { lod = 0; }
  15335. var gl = this._gl;
  15336. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15337. this._bindTextureDirectly(bindTarget, texture, true);
  15338. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15339. this._bindTextureDirectly(bindTarget, null, true);
  15340. };
  15341. /** @hidden */
  15342. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15343. if (faceIndex === void 0) { faceIndex = 0; }
  15344. if (lod === void 0) { lod = 0; }
  15345. var gl = this._gl;
  15346. var textureType = this._getWebGLTextureType(texture.type);
  15347. var format = this._getInternalFormat(texture.format);
  15348. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15349. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15350. this._bindTextureDirectly(bindTarget, texture, true);
  15351. this._unpackFlipY(texture.invertY);
  15352. var target = gl.TEXTURE_2D;
  15353. if (texture.isCube) {
  15354. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15355. }
  15356. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15357. this._bindTextureDirectly(bindTarget, null, true);
  15358. };
  15359. /**
  15360. * Creates a new render target cube texture
  15361. * @param size defines the size of the texture
  15362. * @param options defines the options used to create the texture
  15363. * @returns a new render target cube texture stored in an InternalTexture
  15364. */
  15365. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15366. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15367. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15368. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15369. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15370. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15371. }
  15372. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15373. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15374. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15375. }
  15376. var gl = this._gl;
  15377. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15378. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15379. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15380. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15381. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15382. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15383. }
  15384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15385. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15386. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15387. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15388. for (var face = 0; face < 6; face++) {
  15389. 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);
  15390. }
  15391. // Create the framebuffer
  15392. var framebuffer = gl.createFramebuffer();
  15393. this.bindUnboundFramebuffer(framebuffer);
  15394. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15395. // MipMaps
  15396. if (fullOptions.generateMipMaps) {
  15397. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15398. }
  15399. // Unbind
  15400. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15401. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15402. this.bindUnboundFramebuffer(null);
  15403. texture._framebuffer = framebuffer;
  15404. texture.width = size;
  15405. texture.height = size;
  15406. texture.isReady = true;
  15407. texture.isCube = true;
  15408. texture.samples = 1;
  15409. texture.generateMipMaps = fullOptions.generateMipMaps;
  15410. texture.samplingMode = fullOptions.samplingMode;
  15411. texture.type = fullOptions.type;
  15412. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15413. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15414. this._internalTexturesCache.push(texture);
  15415. return texture;
  15416. };
  15417. /**
  15418. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15419. * @param rootUrl defines the url where the file to load is located
  15420. * @param scene defines the current scene
  15421. * @param lodScale defines scale to apply to the mip map selection
  15422. * @param lodOffset defines offset to apply to the mip map selection
  15423. * @param onLoad defines an optional callback raised when the texture is loaded
  15424. * @param onError defines an optional callback raised if there is an issue to load the texture
  15425. * @param format defines the format of the data
  15426. * @param forcedExtension defines the extension to use to pick the right loader
  15427. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15428. * @returns the cube texture as an InternalTexture
  15429. */
  15430. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15431. var _this = this;
  15432. if (onLoad === void 0) { onLoad = null; }
  15433. if (onError === void 0) { onError = null; }
  15434. if (forcedExtension === void 0) { forcedExtension = null; }
  15435. if (createPolynomials === void 0) { createPolynomials = true; }
  15436. var callback = function (loadData) {
  15437. if (!loadData) {
  15438. if (onLoad) {
  15439. onLoad(null);
  15440. }
  15441. return;
  15442. }
  15443. var texture = loadData.texture;
  15444. if (!createPolynomials) {
  15445. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15446. }
  15447. else if (loadData.info.sphericalPolynomial) {
  15448. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15449. }
  15450. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15451. if (_this._caps.textureLOD) {
  15452. // Do not add extra process if texture lod is supported.
  15453. if (onLoad) {
  15454. onLoad(texture);
  15455. }
  15456. return;
  15457. }
  15458. var mipSlices = 3;
  15459. var gl = _this._gl;
  15460. var width = loadData.width;
  15461. if (!width) {
  15462. return;
  15463. }
  15464. var textures = [];
  15465. for (var i = 0; i < mipSlices; i++) {
  15466. //compute LOD from even spacing in smoothness (matching shader calculation)
  15467. var smoothness = i / (mipSlices - 1);
  15468. var roughness = 1 - smoothness;
  15469. var minLODIndex = lodOffset; // roughness = 0
  15470. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15471. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15472. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15473. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15474. glTextureFromLod.isCube = true;
  15475. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15477. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15478. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15479. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15480. if (loadData.isDDS) {
  15481. var info = loadData.info;
  15482. var data = loadData.data;
  15483. _this._unpackFlipY(info.isCompressed);
  15484. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, true, 6, mipmapIndex);
  15485. }
  15486. else {
  15487. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15488. }
  15489. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15490. // Wrap in a base texture for easy binding.
  15491. var lodTexture = new BABYLON.BaseTexture(scene);
  15492. lodTexture.isCube = true;
  15493. lodTexture._texture = glTextureFromLod;
  15494. glTextureFromLod.isReady = true;
  15495. textures.push(lodTexture);
  15496. }
  15497. texture._lodTextureHigh = textures[2];
  15498. texture._lodTextureMid = textures[1];
  15499. texture._lodTextureLow = textures[0];
  15500. if (onLoad) {
  15501. onLoad(texture);
  15502. }
  15503. };
  15504. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15505. };
  15506. /**
  15507. * Creates a cube texture
  15508. * @param rootUrl defines the url where the files to load is located
  15509. * @param scene defines the current scene
  15510. * @param files defines the list of files to load (1 per face)
  15511. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15512. * @param onLoad defines an optional callback raised when the texture is loaded
  15513. * @param onError defines an optional callback raised if there is an issue to load the texture
  15514. * @param format defines the format of the data
  15515. * @param forcedExtension defines the extension to use to pick the right loader
  15516. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15517. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15518. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15519. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15520. * @returns the cube texture as an InternalTexture
  15521. */
  15522. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15523. var _this = this;
  15524. if (onLoad === void 0) { onLoad = null; }
  15525. if (onError === void 0) { onError = null; }
  15526. if (forcedExtension === void 0) { forcedExtension = null; }
  15527. if (createPolynomials === void 0) { createPolynomials = false; }
  15528. if (lodScale === void 0) { lodScale = 0; }
  15529. if (lodOffset === void 0) { lodOffset = 0; }
  15530. if (fallback === void 0) { fallback = null; }
  15531. var gl = this._gl;
  15532. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15533. texture.isCube = true;
  15534. texture.url = rootUrl;
  15535. texture.generateMipMaps = !noMipmap;
  15536. texture._lodGenerationScale = lodScale;
  15537. texture._lodGenerationOffset = lodOffset;
  15538. if (!this._doNotHandleContextLost) {
  15539. texture._extension = forcedExtension;
  15540. texture._files = files;
  15541. }
  15542. var lastDot = rootUrl.lastIndexOf('.');
  15543. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15544. var loader = null;
  15545. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15546. var availableLoader = _a[_i];
  15547. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15548. loader = availableLoader;
  15549. break;
  15550. }
  15551. }
  15552. var onInternalError = function (request, exception) {
  15553. if (loader) {
  15554. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15555. if (fallbackUrl) {
  15556. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15557. }
  15558. }
  15559. if (onError && request) {
  15560. onError(request.status + " " + request.statusText, exception);
  15561. }
  15562. };
  15563. if (loader) {
  15564. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15565. var onloaddata = function (data) {
  15566. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15567. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15568. };
  15569. if (files && files.length === 6) {
  15570. if (loader.supportCascades) {
  15571. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15572. }
  15573. else if (onError) {
  15574. onError("Textures type does not support cascades.");
  15575. }
  15576. }
  15577. else {
  15578. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15579. }
  15580. }
  15581. else {
  15582. if (!files) {
  15583. throw new Error("Cannot load cubemap because files were not defined");
  15584. }
  15585. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15586. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15587. var height = width;
  15588. _this._prepareWorkingCanvas();
  15589. if (!_this._workingCanvas || !_this._workingContext) {
  15590. return;
  15591. }
  15592. _this._workingCanvas.width = width;
  15593. _this._workingCanvas.height = height;
  15594. var faces = [
  15595. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15596. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15597. ];
  15598. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15599. _this._unpackFlipY(false);
  15600. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15601. for (var index = 0; index < faces.length; index++) {
  15602. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15603. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15604. }
  15605. if (!noMipmap) {
  15606. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15607. }
  15608. _this._setCubeMapTextureParams(!noMipmap);
  15609. texture.width = width;
  15610. texture.height = height;
  15611. texture.isReady = true;
  15612. if (format) {
  15613. texture.format = format;
  15614. }
  15615. texture.onLoadedObservable.notifyObservers(texture);
  15616. texture.onLoadedObservable.clear();
  15617. if (onLoad) {
  15618. onLoad();
  15619. }
  15620. }, files, onError);
  15621. }
  15622. this._internalTexturesCache.push(texture);
  15623. return texture;
  15624. };
  15625. /**
  15626. * @hidden
  15627. */
  15628. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15629. var gl = this._gl;
  15630. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15631. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15632. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15633. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15634. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15635. // this.resetTextureCache();
  15636. };
  15637. /**
  15638. * Update a raw cube texture
  15639. * @param texture defines the texture to udpdate
  15640. * @param data defines the data to store
  15641. * @param format defines the data format
  15642. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15643. * @param invertY defines if data must be stored with Y axis inverted
  15644. * @param compression defines the compression used (null by default)
  15645. * @param level defines which level of the texture to update
  15646. */
  15647. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15648. if (compression === void 0) { compression = null; }
  15649. if (level === void 0) { level = 0; }
  15650. texture._bufferViewArray = data;
  15651. texture.format = format;
  15652. texture.type = type;
  15653. texture.invertY = invertY;
  15654. texture._compression = compression;
  15655. var gl = this._gl;
  15656. var textureType = this._getWebGLTextureType(type);
  15657. var internalFormat = this._getInternalFormat(format);
  15658. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15659. var needConversion = false;
  15660. if (internalFormat === gl.RGB) {
  15661. internalFormat = gl.RGBA;
  15662. needConversion = true;
  15663. }
  15664. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15665. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15666. if (texture.width % 4 !== 0) {
  15667. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15668. }
  15669. // Data are known to be in +X +Y +Z -X -Y -Z
  15670. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15671. var faceData = data[faceIndex];
  15672. if (compression) {
  15673. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15674. }
  15675. else {
  15676. if (needConversion) {
  15677. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15678. }
  15679. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15680. }
  15681. }
  15682. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15683. if (isPot && texture.generateMipMaps && level === 0) {
  15684. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15685. }
  15686. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15687. // this.resetTextureCache();
  15688. texture.isReady = true;
  15689. };
  15690. /**
  15691. * Creates a new raw cube texture
  15692. * @param data defines the array of data to use to create each face
  15693. * @param size defines the size of the textures
  15694. * @param format defines the format of the data
  15695. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15696. * @param generateMipMaps defines if the engine should generate the mip levels
  15697. * @param invertY defines if data must be stored with Y axis inverted
  15698. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15699. * @param compression defines the compression used (null by default)
  15700. * @returns the cube texture as an InternalTexture
  15701. */
  15702. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15703. if (compression === void 0) { compression = null; }
  15704. var gl = this._gl;
  15705. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15706. texture.isCube = true;
  15707. texture.generateMipMaps = generateMipMaps;
  15708. texture.format = format;
  15709. texture.type = type;
  15710. if (!this._doNotHandleContextLost) {
  15711. texture._bufferViewArray = data;
  15712. }
  15713. var textureType = this._getWebGLTextureType(type);
  15714. var internalFormat = this._getInternalFormat(format);
  15715. if (internalFormat === gl.RGB) {
  15716. internalFormat = gl.RGBA;
  15717. }
  15718. var width = size;
  15719. var height = width;
  15720. texture.width = width;
  15721. texture.height = height;
  15722. // Double check on POT to generate Mips.
  15723. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15724. if (!isPot) {
  15725. generateMipMaps = false;
  15726. }
  15727. // Upload data if needed. The texture won't be ready until then.
  15728. if (data) {
  15729. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15730. }
  15731. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15732. // Filters
  15733. if (data && generateMipMaps) {
  15734. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15735. }
  15736. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15737. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15738. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15739. }
  15740. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15741. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15742. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15743. }
  15744. else {
  15745. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15746. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15748. }
  15749. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15750. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15751. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15752. return texture;
  15753. };
  15754. /**
  15755. * Creates a new raw cube texture from a specified url
  15756. * @param url defines the url where the data is located
  15757. * @param scene defines the current scene
  15758. * @param size defines the size of the textures
  15759. * @param format defines the format of the data
  15760. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15761. * @param noMipmap defines if the engine should avoid generating the mip levels
  15762. * @param callback defines a callback used to extract texture data from loaded data
  15763. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15764. * @param onLoad defines a callback called when texture is loaded
  15765. * @param onError defines a callback called if there is an error
  15766. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15767. * @param invertY defines if data must be stored with Y axis inverted
  15768. * @returns the cube texture as an InternalTexture
  15769. */
  15770. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15771. var _this = this;
  15772. if (onLoad === void 0) { onLoad = null; }
  15773. if (onError === void 0) { onError = null; }
  15774. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15775. if (invertY === void 0) { invertY = false; }
  15776. var gl = this._gl;
  15777. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15778. scene._addPendingData(texture);
  15779. texture.url = url;
  15780. this._internalTexturesCache.push(texture);
  15781. var onerror = function (request, exception) {
  15782. scene._removePendingData(texture);
  15783. if (onError && request) {
  15784. onError(request.status + " " + request.statusText, exception);
  15785. }
  15786. };
  15787. var internalCallback = function (data) {
  15788. var width = texture.width;
  15789. var faceDataArrays = callback(data);
  15790. if (!faceDataArrays) {
  15791. return;
  15792. }
  15793. if (mipmapGenerator) {
  15794. var textureType = _this._getWebGLTextureType(type);
  15795. var internalFormat = _this._getInternalFormat(format);
  15796. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15797. var needConversion = false;
  15798. if (internalFormat === gl.RGB) {
  15799. internalFormat = gl.RGBA;
  15800. needConversion = true;
  15801. }
  15802. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15803. _this._unpackFlipY(false);
  15804. var mipData = mipmapGenerator(faceDataArrays);
  15805. for (var level = 0; level < mipData.length; level++) {
  15806. var mipSize = width >> level;
  15807. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15808. var mipFaceData = mipData[level][faceIndex];
  15809. if (needConversion) {
  15810. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15811. }
  15812. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15813. }
  15814. }
  15815. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15816. }
  15817. else {
  15818. texture.generateMipMaps = !noMipmap;
  15819. if (type === Engine.TEXTURETYPE_FLOAT && !_this._caps.textureFloatLinearFiltering) {
  15820. texture.generateMipMaps = false;
  15821. }
  15822. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15823. }
  15824. texture.isReady = true;
  15825. // this.resetTextureCache();
  15826. scene._removePendingData(texture);
  15827. if (onLoad) {
  15828. onLoad();
  15829. }
  15830. };
  15831. this._loadFile(url, function (data) {
  15832. internalCallback(data);
  15833. }, undefined, scene.database, true, onerror);
  15834. return texture;
  15835. };
  15836. ;
  15837. /**
  15838. * Update a raw 3D texture
  15839. * @param texture defines the texture to update
  15840. * @param data defines the data to store
  15841. * @param format defines the data format
  15842. * @param invertY defines if data must be stored with Y axis inverted
  15843. * @param compression defines the used compression (can be null)
  15844. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15845. */
  15846. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15847. if (compression === void 0) { compression = null; }
  15848. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15849. var internalType = this._getWebGLTextureType(textureType);
  15850. var internalFormat = this._getInternalFormat(format);
  15851. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15852. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15853. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15854. if (!this._doNotHandleContextLost) {
  15855. texture._bufferView = data;
  15856. texture.format = format;
  15857. texture.invertY = invertY;
  15858. texture._compression = compression;
  15859. }
  15860. if (texture.width % 4 !== 0) {
  15861. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15862. }
  15863. if (compression && data) {
  15864. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15865. }
  15866. else {
  15867. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15868. }
  15869. if (texture.generateMipMaps) {
  15870. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15871. }
  15872. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15873. // this.resetTextureCache();
  15874. texture.isReady = true;
  15875. };
  15876. /**
  15877. * Creates a new raw 3D texture
  15878. * @param data defines the data used to create the texture
  15879. * @param width defines the width of the texture
  15880. * @param height defines the height of the texture
  15881. * @param depth defines the depth of the texture
  15882. * @param format defines the format of the texture
  15883. * @param generateMipMaps defines if the engine must generate mip levels
  15884. * @param invertY defines if data must be stored with Y axis inverted
  15885. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15886. * @param compression defines the compressed used (can be null)
  15887. * @param textureType defines the compressed used (can be null)
  15888. * @returns a new raw 3D texture (stored in an InternalTexture)
  15889. */
  15890. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15891. if (compression === void 0) { compression = null; }
  15892. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15893. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15894. texture.baseWidth = width;
  15895. texture.baseHeight = height;
  15896. texture.baseDepth = depth;
  15897. texture.width = width;
  15898. texture.height = height;
  15899. texture.depth = depth;
  15900. texture.format = format;
  15901. texture.type = textureType;
  15902. texture.generateMipMaps = generateMipMaps;
  15903. texture.samplingMode = samplingMode;
  15904. texture.is3D = true;
  15905. if (!this._doNotHandleContextLost) {
  15906. texture._bufferView = data;
  15907. }
  15908. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15909. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15910. // Filters
  15911. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15912. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15913. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15914. if (generateMipMaps) {
  15915. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15916. }
  15917. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15918. this._internalTexturesCache.push(texture);
  15919. return texture;
  15920. };
  15921. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15922. var gl = this._gl;
  15923. if (!gl) {
  15924. return;
  15925. }
  15926. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  15927. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15928. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15929. if (!noMipmap && !isCompressed) {
  15930. gl.generateMipmap(gl.TEXTURE_2D);
  15931. }
  15932. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15933. // this.resetTextureCache();
  15934. if (scene) {
  15935. scene._removePendingData(texture);
  15936. }
  15937. texture.onLoadedObservable.notifyObservers(texture);
  15938. texture.onLoadedObservable.clear();
  15939. };
  15940. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15941. var _this = this;
  15942. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15943. var maxTextureSize = this.getCaps().maxTextureSize;
  15944. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  15945. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  15946. var gl = this._gl;
  15947. if (!gl) {
  15948. return;
  15949. }
  15950. if (!texture._webGLTexture) {
  15951. // this.resetTextureCache();
  15952. if (scene) {
  15953. scene._removePendingData(texture);
  15954. }
  15955. return;
  15956. }
  15957. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15958. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15959. texture.baseWidth = width;
  15960. texture.baseHeight = height;
  15961. texture.width = potWidth;
  15962. texture.height = potHeight;
  15963. texture.isReady = true;
  15964. if (processFunction(potWidth, potHeight, function () {
  15965. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15966. })) {
  15967. // Returning as texture needs extra async steps
  15968. return;
  15969. }
  15970. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15971. };
  15972. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15973. // Create new RGBA data container.
  15974. var rgbaData;
  15975. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15976. rgbaData = new Float32Array(width * height * 4);
  15977. }
  15978. else {
  15979. rgbaData = new Uint32Array(width * height * 4);
  15980. }
  15981. // Convert each pixel.
  15982. for (var x = 0; x < width; x++) {
  15983. for (var y = 0; y < height; y++) {
  15984. var index = (y * width + x) * 3;
  15985. var newIndex = (y * width + x) * 4;
  15986. // Map Old Value to new value.
  15987. rgbaData[newIndex + 0] = rgbData[index + 0];
  15988. rgbaData[newIndex + 1] = rgbData[index + 1];
  15989. rgbaData[newIndex + 2] = rgbData[index + 2];
  15990. // Add fully opaque alpha channel.
  15991. rgbaData[newIndex + 3] = 1;
  15992. }
  15993. }
  15994. return rgbaData;
  15995. };
  15996. /** @hidden */
  15997. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15998. var gl = this._gl;
  15999. if (texture._framebuffer) {
  16000. gl.deleteFramebuffer(texture._framebuffer);
  16001. texture._framebuffer = null;
  16002. }
  16003. if (texture._depthStencilBuffer) {
  16004. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16005. texture._depthStencilBuffer = null;
  16006. }
  16007. if (texture._MSAAFramebuffer) {
  16008. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16009. texture._MSAAFramebuffer = null;
  16010. }
  16011. if (texture._MSAARenderBuffer) {
  16012. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16013. texture._MSAARenderBuffer = null;
  16014. }
  16015. };
  16016. /** @hidden */
  16017. Engine.prototype._releaseTexture = function (texture) {
  16018. var gl = this._gl;
  16019. this._releaseFramebufferObjects(texture);
  16020. gl.deleteTexture(texture._webGLTexture);
  16021. // Unbind channels
  16022. this.unbindAllTextures();
  16023. var index = this._internalTexturesCache.indexOf(texture);
  16024. if (index !== -1) {
  16025. this._internalTexturesCache.splice(index, 1);
  16026. }
  16027. // Integrated fixed lod samplers.
  16028. if (texture._lodTextureHigh) {
  16029. texture._lodTextureHigh.dispose();
  16030. }
  16031. if (texture._lodTextureMid) {
  16032. texture._lodTextureMid.dispose();
  16033. }
  16034. if (texture._lodTextureLow) {
  16035. texture._lodTextureLow.dispose();
  16036. }
  16037. // Set output texture of post process to null if the texture has been released/disposed
  16038. this.scenes.forEach(function (scene) {
  16039. scene.postProcesses.forEach(function (postProcess) {
  16040. if (postProcess._outputTexture == texture) {
  16041. postProcess._outputTexture = null;
  16042. }
  16043. });
  16044. scene.cameras.forEach(function (camera) {
  16045. camera._postProcesses.forEach(function (postProcess) {
  16046. if (postProcess) {
  16047. if (postProcess._outputTexture == texture) {
  16048. postProcess._outputTexture = null;
  16049. }
  16050. }
  16051. });
  16052. });
  16053. });
  16054. };
  16055. Engine.prototype.setProgram = function (program) {
  16056. if (this._currentProgram !== program) {
  16057. this._gl.useProgram(program);
  16058. this._currentProgram = program;
  16059. }
  16060. };
  16061. /**
  16062. * Binds an effect to the webGL context
  16063. * @param effect defines the effect to bind
  16064. */
  16065. Engine.prototype.bindSamplers = function (effect) {
  16066. this.setProgram(effect.getProgram());
  16067. var samplers = effect.getSamplers();
  16068. for (var index = 0; index < samplers.length; index++) {
  16069. var uniform = effect.getUniform(samplers[index]);
  16070. if (uniform) {
  16071. this._boundUniforms[index] = uniform;
  16072. }
  16073. }
  16074. this._currentEffect = null;
  16075. };
  16076. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16077. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16078. return;
  16079. }
  16080. // Remove
  16081. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16082. // Bind last to it
  16083. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16084. // Bind to dummy
  16085. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16086. };
  16087. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16088. if (!internalTexture) {
  16089. return -1;
  16090. }
  16091. internalTexture._initialSlot = channel;
  16092. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16093. if (channel !== internalTexture._designatedSlot) {
  16094. this._textureCollisions.addCount(1, false);
  16095. }
  16096. }
  16097. else {
  16098. if (channel !== internalTexture._designatedSlot) {
  16099. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16100. return internalTexture._designatedSlot;
  16101. }
  16102. else {
  16103. // No slot for this texture, let's pick a new one (if we find a free slot)
  16104. if (this._nextFreeTextureSlots.length) {
  16105. return this._nextFreeTextureSlots[0];
  16106. }
  16107. // We need to recycle the oldest bound texture, sorry.
  16108. this._textureCollisions.addCount(1, false);
  16109. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16110. }
  16111. }
  16112. }
  16113. return channel;
  16114. };
  16115. Engine.prototype._linkTrackers = function (previous, next) {
  16116. previous.next = next;
  16117. next.previous = previous;
  16118. };
  16119. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16120. var currentSlot = internalTexture._designatedSlot;
  16121. if (currentSlot === -1) {
  16122. return -1;
  16123. }
  16124. internalTexture._designatedSlot = -1;
  16125. if (this.disableTextureBindingOptimization) {
  16126. return -1;
  16127. }
  16128. // Remove from bound list
  16129. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16130. // Free the slot
  16131. this._boundTexturesCache[currentSlot] = null;
  16132. this._nextFreeTextureSlots.push(currentSlot);
  16133. return currentSlot;
  16134. };
  16135. Engine.prototype._activateCurrentTexture = function () {
  16136. if (this._currentTextureChannel !== this._activeChannel) {
  16137. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16138. this._currentTextureChannel = this._activeChannel;
  16139. }
  16140. };
  16141. /** @hidden */
  16142. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16143. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16144. if (force === void 0) { force = false; }
  16145. var wasPreviouslyBound = false;
  16146. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16147. this._activeChannel = texture._designatedSlot;
  16148. }
  16149. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16150. var isTextureForRendering = texture && texture._initialSlot > -1;
  16151. if (currentTextureBound !== texture || force) {
  16152. if (currentTextureBound) {
  16153. this._removeDesignatedSlot(currentTextureBound);
  16154. }
  16155. this._activateCurrentTexture();
  16156. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16157. this._boundTexturesCache[this._activeChannel] = texture;
  16158. if (texture) {
  16159. if (!this.disableTextureBindingOptimization) {
  16160. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16161. if (slotIndex > -1) {
  16162. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16163. }
  16164. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16165. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16166. }
  16167. texture._designatedSlot = this._activeChannel;
  16168. }
  16169. }
  16170. else if (forTextureDataUpdate) {
  16171. wasPreviouslyBound = true;
  16172. this._activateCurrentTexture();
  16173. }
  16174. if (isTextureForRendering && !forTextureDataUpdate) {
  16175. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16176. }
  16177. return wasPreviouslyBound;
  16178. };
  16179. /** @hidden */
  16180. Engine.prototype._bindTexture = function (channel, texture) {
  16181. if (channel < 0) {
  16182. return;
  16183. }
  16184. if (texture) {
  16185. channel = this._getCorrectTextureChannel(channel, texture);
  16186. }
  16187. this._activeChannel = channel;
  16188. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16189. };
  16190. /**
  16191. * Sets a texture to the webGL context from a postprocess
  16192. * @param channel defines the channel to use
  16193. * @param postProcess defines the source postprocess
  16194. */
  16195. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16196. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16197. };
  16198. /**
  16199. * Binds the output of the passed in post process to the texture channel specified
  16200. * @param channel The channel the texture should be bound to
  16201. * @param postProcess The post process which's output should be bound
  16202. */
  16203. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16204. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16205. };
  16206. /**
  16207. * Unbind all textures from the webGL context
  16208. */
  16209. Engine.prototype.unbindAllTextures = function () {
  16210. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16211. this._activeChannel = channel;
  16212. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16213. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16214. if (this.webGLVersion > 1) {
  16215. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16216. }
  16217. }
  16218. };
  16219. /**
  16220. * Sets a texture to the according uniform.
  16221. * @param channel The texture channel
  16222. * @param uniform The uniform to set
  16223. * @param texture The texture to apply
  16224. */
  16225. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16226. if (channel < 0) {
  16227. return;
  16228. }
  16229. if (uniform) {
  16230. this._boundUniforms[channel] = uniform;
  16231. }
  16232. this._setTexture(channel, texture);
  16233. };
  16234. /**
  16235. * Sets a depth stencil texture from a render target to the according uniform.
  16236. * @param channel The texture channel
  16237. * @param uniform The uniform to set
  16238. * @param texture The render target texture containing the depth stencil texture to apply
  16239. */
  16240. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16241. if (channel < 0) {
  16242. return;
  16243. }
  16244. if (uniform) {
  16245. this._boundUniforms[channel] = uniform;
  16246. }
  16247. if (!texture || !texture.depthStencilTexture) {
  16248. this._setTexture(channel, null);
  16249. }
  16250. else {
  16251. this._setTexture(channel, texture, false, true);
  16252. }
  16253. };
  16254. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16255. var uniform = this._boundUniforms[sourceSlot];
  16256. if (uniform._currentState === destination) {
  16257. return;
  16258. }
  16259. this._gl.uniform1i(uniform, destination);
  16260. uniform._currentState = destination;
  16261. };
  16262. Engine.prototype._getTextureWrapMode = function (mode) {
  16263. switch (mode) {
  16264. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16265. return this._gl.REPEAT;
  16266. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16267. return this._gl.CLAMP_TO_EDGE;
  16268. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16269. return this._gl.MIRRORED_REPEAT;
  16270. }
  16271. return this._gl.REPEAT;
  16272. };
  16273. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16274. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16275. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16276. // Not ready?
  16277. if (!texture) {
  16278. if (this._boundTexturesCache[channel] != null) {
  16279. this._activeChannel = channel;
  16280. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16281. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16282. if (this.webGLVersion > 1) {
  16283. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16284. }
  16285. }
  16286. return false;
  16287. }
  16288. // Video
  16289. if (texture.video) {
  16290. this._activeChannel = channel;
  16291. texture.update();
  16292. }
  16293. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16294. texture.delayLoad();
  16295. return false;
  16296. }
  16297. var internalTexture;
  16298. if (depthStencilTexture) {
  16299. internalTexture = texture.depthStencilTexture;
  16300. }
  16301. else if (texture.isReady()) {
  16302. internalTexture = texture.getInternalTexture();
  16303. }
  16304. else if (texture.isCube) {
  16305. internalTexture = this.emptyCubeTexture;
  16306. }
  16307. else if (texture.is3D) {
  16308. internalTexture = this.emptyTexture3D;
  16309. }
  16310. else {
  16311. internalTexture = this.emptyTexture;
  16312. }
  16313. if (!isPartOfTextureArray) {
  16314. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16315. }
  16316. var needToBind = true;
  16317. if (this._boundTexturesCache[channel] === internalTexture) {
  16318. this._moveBoundTextureOnTop(internalTexture);
  16319. if (!isPartOfTextureArray) {
  16320. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16321. }
  16322. needToBind = false;
  16323. }
  16324. this._activeChannel = channel;
  16325. if (internalTexture && internalTexture.is3D) {
  16326. if (needToBind) {
  16327. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16328. }
  16329. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16330. internalTexture._cachedWrapU = texture.wrapU;
  16331. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16332. }
  16333. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16334. internalTexture._cachedWrapV = texture.wrapV;
  16335. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16336. }
  16337. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16338. internalTexture._cachedWrapR = texture.wrapR;
  16339. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16340. }
  16341. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16342. }
  16343. else if (internalTexture && internalTexture.isCube) {
  16344. if (needToBind) {
  16345. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16346. }
  16347. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16348. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16349. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16350. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16351. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16352. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16353. }
  16354. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16355. }
  16356. else {
  16357. if (needToBind) {
  16358. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16359. }
  16360. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16361. internalTexture._cachedWrapU = texture.wrapU;
  16362. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16363. }
  16364. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16365. internalTexture._cachedWrapV = texture.wrapV;
  16366. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16367. }
  16368. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16369. }
  16370. return true;
  16371. };
  16372. /**
  16373. * Sets an array of texture to the webGL context
  16374. * @param channel defines the channel where the texture array must be set
  16375. * @param uniform defines the associated uniform location
  16376. * @param textures defines the array of textures to bind
  16377. */
  16378. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16379. if (channel < 0 || !uniform) {
  16380. return;
  16381. }
  16382. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16383. this._textureUnits = new Int32Array(textures.length);
  16384. }
  16385. for (var i = 0; i < textures.length; i++) {
  16386. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16387. }
  16388. this._gl.uniform1iv(uniform, this._textureUnits);
  16389. for (var index = 0; index < textures.length; index++) {
  16390. this._setTexture(this._textureUnits[index], textures[index], true);
  16391. }
  16392. };
  16393. /** @hidden */
  16394. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16395. var internalTexture = texture.getInternalTexture();
  16396. if (!internalTexture) {
  16397. return;
  16398. }
  16399. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16400. var value = texture.anisotropicFilteringLevel;
  16401. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16402. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16403. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16404. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16405. }
  16406. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16407. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16408. internalTexture._cachedAnisotropicFilteringLevel = value;
  16409. }
  16410. };
  16411. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16412. this._bindTextureDirectly(target, texture, true, true);
  16413. this._gl.texParameterf(target, parameter, value);
  16414. };
  16415. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16416. if (texture) {
  16417. this._bindTextureDirectly(target, texture, true, true);
  16418. }
  16419. this._gl.texParameteri(target, parameter, value);
  16420. };
  16421. /**
  16422. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16423. * @param x defines the x coordinate of the rectangle where pixels must be read
  16424. * @param y defines the y coordinate of the rectangle where pixels must be read
  16425. * @param width defines the width of the rectangle where pixels must be read
  16426. * @param height defines the height of the rectangle where pixels must be read
  16427. * @returns a Uint8Array containing RGBA colors
  16428. */
  16429. Engine.prototype.readPixels = function (x, y, width, height) {
  16430. var data = new Uint8Array(height * width * 4);
  16431. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16432. return data;
  16433. };
  16434. /**
  16435. * Add an externaly attached data from its key.
  16436. * This method call will fail and return false, if such key already exists.
  16437. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16438. * @param key the unique key that identifies the data
  16439. * @param data the data object to associate to the key for this Engine instance
  16440. * @return true if no such key were already present and the data was added successfully, false otherwise
  16441. */
  16442. Engine.prototype.addExternalData = function (key, data) {
  16443. if (!this._externalData) {
  16444. this._externalData = new BABYLON.StringDictionary();
  16445. }
  16446. return this._externalData.add(key, data);
  16447. };
  16448. /**
  16449. * Get an externaly attached data from its key
  16450. * @param key the unique key that identifies the data
  16451. * @return the associated data, if present (can be null), or undefined if not present
  16452. */
  16453. Engine.prototype.getExternalData = function (key) {
  16454. if (!this._externalData) {
  16455. this._externalData = new BABYLON.StringDictionary();
  16456. }
  16457. return this._externalData.get(key);
  16458. };
  16459. /**
  16460. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16461. * @param key the unique key that identifies the data
  16462. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16463. * @return the associated data, can be null if the factory returned null.
  16464. */
  16465. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16466. if (!this._externalData) {
  16467. this._externalData = new BABYLON.StringDictionary();
  16468. }
  16469. return this._externalData.getOrAddWithFactory(key, factory);
  16470. };
  16471. /**
  16472. * Remove an externaly attached data from the Engine instance
  16473. * @param key the unique key that identifies the data
  16474. * @return true if the data was successfully removed, false if it doesn't exist
  16475. */
  16476. Engine.prototype.removeExternalData = function (key) {
  16477. if (!this._externalData) {
  16478. this._externalData = new BABYLON.StringDictionary();
  16479. }
  16480. return this._externalData.remove(key);
  16481. };
  16482. /**
  16483. * Unbind all vertex attributes from the webGL context
  16484. */
  16485. Engine.prototype.unbindAllAttributes = function () {
  16486. if (this._mustWipeVertexAttributes) {
  16487. this._mustWipeVertexAttributes = false;
  16488. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16489. this._gl.disableVertexAttribArray(i);
  16490. this._vertexAttribArraysEnabled[i] = false;
  16491. this._currentBufferPointers[i].active = false;
  16492. }
  16493. return;
  16494. }
  16495. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16496. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16497. continue;
  16498. }
  16499. this._gl.disableVertexAttribArray(i);
  16500. this._vertexAttribArraysEnabled[i] = false;
  16501. this._currentBufferPointers[i].active = false;
  16502. }
  16503. };
  16504. /**
  16505. * 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
  16506. */
  16507. Engine.prototype.releaseEffects = function () {
  16508. for (var name in this._compiledEffects) {
  16509. this._deleteProgram(this._compiledEffects[name]._program);
  16510. }
  16511. this._compiledEffects = {};
  16512. };
  16513. /**
  16514. * Dispose and release all associated resources
  16515. */
  16516. Engine.prototype.dispose = function () {
  16517. this.hideLoadingUI();
  16518. this.stopRenderLoop();
  16519. // Release postProcesses
  16520. while (this.postProcesses.length) {
  16521. this.postProcesses[0].dispose();
  16522. }
  16523. // Empty texture
  16524. if (this._emptyTexture) {
  16525. this._releaseTexture(this._emptyTexture);
  16526. this._emptyTexture = null;
  16527. }
  16528. if (this._emptyCubeTexture) {
  16529. this._releaseTexture(this._emptyCubeTexture);
  16530. this._emptyCubeTexture = null;
  16531. }
  16532. // Rescale PP
  16533. if (this._rescalePostProcess) {
  16534. this._rescalePostProcess.dispose();
  16535. }
  16536. // Release scenes
  16537. while (this.scenes.length) {
  16538. this.scenes[0].dispose();
  16539. }
  16540. // Release audio engine
  16541. if (Engine.audioEngine) {
  16542. Engine.audioEngine.dispose();
  16543. }
  16544. // Release effects
  16545. this.releaseEffects();
  16546. // Unbind
  16547. this.unbindAllAttributes();
  16548. this._boundUniforms = [];
  16549. if (this._dummyFramebuffer) {
  16550. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16551. }
  16552. //WebVR
  16553. this.disableVR();
  16554. // Events
  16555. if (BABYLON.Tools.IsWindowObjectExist()) {
  16556. window.removeEventListener("blur", this._onBlur);
  16557. window.removeEventListener("focus", this._onFocus);
  16558. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16559. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16560. if (this._renderingCanvas) {
  16561. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16562. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16563. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16564. if (!this._doNotHandleContextLost) {
  16565. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16566. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16567. }
  16568. }
  16569. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16570. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16571. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16572. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16573. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16574. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16575. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16576. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16577. if (this._onVrDisplayConnect) {
  16578. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16579. if (this._onVrDisplayDisconnect) {
  16580. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16581. }
  16582. if (this._onVrDisplayPresentChange) {
  16583. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16584. }
  16585. this._onVrDisplayConnect = null;
  16586. this._onVrDisplayDisconnect = null;
  16587. }
  16588. }
  16589. // Remove from Instances
  16590. var index = Engine.Instances.indexOf(this);
  16591. if (index >= 0) {
  16592. Engine.Instances.splice(index, 1);
  16593. }
  16594. this._workingCanvas = null;
  16595. this._workingContext = null;
  16596. this._currentBufferPointers = [];
  16597. this._renderingCanvas = null;
  16598. this._currentProgram = null;
  16599. this._bindedRenderFunction = null;
  16600. this.onResizeObservable.clear();
  16601. this.onCanvasBlurObservable.clear();
  16602. this.onCanvasFocusObservable.clear();
  16603. this.onCanvasPointerOutObservable.clear();
  16604. this.onBeginFrameObservable.clear();
  16605. this.onEndFrameObservable.clear();
  16606. BABYLON.Effect.ResetCache();
  16607. // Abort active requests
  16608. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16609. var request = _a[_i];
  16610. request.abort();
  16611. }
  16612. };
  16613. // Loading screen
  16614. /**
  16615. * Display the loading screen
  16616. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16617. */
  16618. Engine.prototype.displayLoadingUI = function () {
  16619. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16620. return;
  16621. }
  16622. var loadingScreen = this.loadingScreen;
  16623. if (loadingScreen) {
  16624. loadingScreen.displayLoadingUI();
  16625. }
  16626. };
  16627. /**
  16628. * Hide the loading screen
  16629. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16630. */
  16631. Engine.prototype.hideLoadingUI = function () {
  16632. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16633. return;
  16634. }
  16635. var loadingScreen = this.loadingScreen;
  16636. if (loadingScreen) {
  16637. loadingScreen.hideLoadingUI();
  16638. }
  16639. };
  16640. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16641. /**
  16642. * Gets the current loading screen object
  16643. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16644. */
  16645. get: function () {
  16646. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16647. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16648. return this._loadingScreen;
  16649. },
  16650. /**
  16651. * Sets the current loading screen object
  16652. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16653. */
  16654. set: function (loadingScreen) {
  16655. this._loadingScreen = loadingScreen;
  16656. },
  16657. enumerable: true,
  16658. configurable: true
  16659. });
  16660. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16661. /**
  16662. * Sets the current loading screen text
  16663. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16664. */
  16665. set: function (text) {
  16666. this.loadingScreen.loadingUIText = text;
  16667. },
  16668. enumerable: true,
  16669. configurable: true
  16670. });
  16671. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16672. /**
  16673. * Sets the current loading screen background color
  16674. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16675. */
  16676. set: function (color) {
  16677. this.loadingScreen.loadingUIBackgroundColor = color;
  16678. },
  16679. enumerable: true,
  16680. configurable: true
  16681. });
  16682. /**
  16683. * Attach a new callback raised when context lost event is fired
  16684. * @param callback defines the callback to call
  16685. */
  16686. Engine.prototype.attachContextLostEvent = function (callback) {
  16687. if (this._renderingCanvas) {
  16688. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16689. }
  16690. };
  16691. /**
  16692. * Attach a new callback raised when context restored event is fired
  16693. * @param callback defines the callback to call
  16694. */
  16695. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16696. if (this._renderingCanvas) {
  16697. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16698. }
  16699. };
  16700. /**
  16701. * Gets the source code of the vertex shader associated with a specific webGL program
  16702. * @param program defines the program to use
  16703. * @returns a string containing the source code of the vertex shader associated with the program
  16704. */
  16705. Engine.prototype.getVertexShaderSource = function (program) {
  16706. var shaders = this._gl.getAttachedShaders(program);
  16707. if (!shaders) {
  16708. return null;
  16709. }
  16710. return this._gl.getShaderSource(shaders[0]);
  16711. };
  16712. /**
  16713. * Gets the source code of the fragment shader associated with a specific webGL program
  16714. * @param program defines the program to use
  16715. * @returns a string containing the source code of the fragment shader associated with the program
  16716. */
  16717. Engine.prototype.getFragmentShaderSource = function (program) {
  16718. var shaders = this._gl.getAttachedShaders(program);
  16719. if (!shaders) {
  16720. return null;
  16721. }
  16722. return this._gl.getShaderSource(shaders[1]);
  16723. };
  16724. /**
  16725. * Get the current error code of the webGL context
  16726. * @returns the error code
  16727. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16728. */
  16729. Engine.prototype.getError = function () {
  16730. return this._gl.getError();
  16731. };
  16732. // FPS
  16733. /**
  16734. * Gets the current framerate
  16735. * @returns a number representing the framerate
  16736. */
  16737. Engine.prototype.getFps = function () {
  16738. return this._fps;
  16739. };
  16740. /**
  16741. * Gets the time spent between current and previous frame
  16742. * @returns a number representing the delta time in ms
  16743. */
  16744. Engine.prototype.getDeltaTime = function () {
  16745. return this._deltaTime;
  16746. };
  16747. Engine.prototype._measureFps = function () {
  16748. this._performanceMonitor.sampleFrame();
  16749. this._fps = this._performanceMonitor.averageFPS;
  16750. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16751. };
  16752. /** @hidden */
  16753. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16754. if (faceIndex === void 0) { faceIndex = -1; }
  16755. if (level === void 0) { level = 0; }
  16756. var gl = this._gl;
  16757. if (!this._dummyFramebuffer) {
  16758. var dummy = gl.createFramebuffer();
  16759. if (!dummy) {
  16760. throw new Error("Unable to create dummy framebuffer");
  16761. }
  16762. this._dummyFramebuffer = dummy;
  16763. }
  16764. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16765. if (faceIndex > -1) {
  16766. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16767. }
  16768. else {
  16769. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16770. }
  16771. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16772. var buffer;
  16773. switch (readType) {
  16774. case gl.UNSIGNED_BYTE:
  16775. buffer = new Uint8Array(4 * width * height);
  16776. readType = gl.UNSIGNED_BYTE;
  16777. break;
  16778. default:
  16779. buffer = new Float32Array(4 * width * height);
  16780. readType = gl.FLOAT;
  16781. break;
  16782. }
  16783. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16784. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16785. return buffer;
  16786. };
  16787. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16788. if (this._webGLVersion > 1) {
  16789. return this._caps.colorBufferFloat;
  16790. }
  16791. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16792. };
  16793. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16794. if (this._webGLVersion > 1) {
  16795. return this._caps.colorBufferFloat;
  16796. }
  16797. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16798. };
  16799. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16800. Engine.prototype._canRenderToFramebuffer = function (type) {
  16801. var gl = this._gl;
  16802. //clear existing errors
  16803. while (gl.getError() !== gl.NO_ERROR) { }
  16804. var successful = true;
  16805. var texture = gl.createTexture();
  16806. gl.bindTexture(gl.TEXTURE_2D, texture);
  16807. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16808. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16809. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16810. var fb = gl.createFramebuffer();
  16811. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16812. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16813. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16814. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16815. successful = successful && (gl.getError() === gl.NO_ERROR);
  16816. //try render by clearing frame buffer's color buffer
  16817. if (successful) {
  16818. gl.clear(gl.COLOR_BUFFER_BIT);
  16819. successful = successful && (gl.getError() === gl.NO_ERROR);
  16820. }
  16821. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16822. if (successful) {
  16823. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16824. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16825. var readFormat = gl.RGBA;
  16826. var readType = gl.UNSIGNED_BYTE;
  16827. var buffer = new Uint8Array(4);
  16828. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16829. successful = successful && (gl.getError() === gl.NO_ERROR);
  16830. }
  16831. //clean up
  16832. gl.deleteTexture(texture);
  16833. gl.deleteFramebuffer(fb);
  16834. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16835. //clear accumulated errors
  16836. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16837. return successful;
  16838. };
  16839. /** @hidden */
  16840. Engine.prototype._getWebGLTextureType = function (type) {
  16841. if (type === Engine.TEXTURETYPE_FLOAT) {
  16842. return this._gl.FLOAT;
  16843. }
  16844. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16845. // Add Half Float Constant.
  16846. return this._gl.HALF_FLOAT_OES;
  16847. }
  16848. return this._gl.UNSIGNED_BYTE;
  16849. };
  16850. ;
  16851. Engine.prototype._getInternalFormat = function (format) {
  16852. var internalFormat = this._gl.RGBA;
  16853. switch (format) {
  16854. case Engine.TEXTUREFORMAT_ALPHA:
  16855. internalFormat = this._gl.ALPHA;
  16856. break;
  16857. case Engine.TEXTUREFORMAT_LUMINANCE:
  16858. internalFormat = this._gl.LUMINANCE;
  16859. break;
  16860. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16861. internalFormat = this._gl.LUMINANCE_ALPHA;
  16862. break;
  16863. case Engine.TEXTUREFORMAT_RGB:
  16864. internalFormat = this._gl.RGB;
  16865. break;
  16866. case Engine.TEXTUREFORMAT_RGBA:
  16867. internalFormat = this._gl.RGBA;
  16868. break;
  16869. case Engine.TEXTUREFORMAT_R:
  16870. internalFormat = this._gl.RED;
  16871. break;
  16872. case Engine.TEXTUREFORMAT_RG:
  16873. internalFormat = this._gl.RG;
  16874. break;
  16875. }
  16876. return internalFormat;
  16877. };
  16878. /** @hidden */
  16879. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16880. if (this._webGLVersion === 1) {
  16881. if (format !== undefined) {
  16882. switch (format) {
  16883. case Engine.TEXTUREFORMAT_LUMINANCE:
  16884. return this._gl.LUMINANCE;
  16885. case Engine.TEXTUREFORMAT_ALPHA:
  16886. return this._gl.ALPHA;
  16887. }
  16888. }
  16889. return this._gl.RGBA;
  16890. }
  16891. if (type === Engine.TEXTURETYPE_FLOAT) {
  16892. if (format !== undefined) {
  16893. switch (format) {
  16894. case Engine.TEXTUREFORMAT_R:
  16895. return this._gl.R32F;
  16896. case Engine.TEXTUREFORMAT_RG:
  16897. return this._gl.RG32F;
  16898. case Engine.TEXTUREFORMAT_RGB:
  16899. return this._gl.RGB32F;
  16900. }
  16901. }
  16902. return this._gl.RGBA32F;
  16903. }
  16904. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16905. if (format) {
  16906. switch (format) {
  16907. case Engine.TEXTUREFORMAT_R:
  16908. return this._gl.R16F;
  16909. case Engine.TEXTUREFORMAT_RG:
  16910. return this._gl.RG16F;
  16911. case Engine.TEXTUREFORMAT_RGB:
  16912. return this._gl.RGB16F;
  16913. }
  16914. }
  16915. return this._gl.RGBA16F;
  16916. }
  16917. if (format !== undefined) {
  16918. switch (format) {
  16919. case Engine.TEXTUREFORMAT_LUMINANCE:
  16920. return this._gl.LUMINANCE;
  16921. case Engine.TEXTUREFORMAT_RGB:
  16922. return this._gl.RGB;
  16923. case Engine.TEXTUREFORMAT_R:
  16924. return this._gl.R8;
  16925. case Engine.TEXTUREFORMAT_RG:
  16926. return this._gl.RG8;
  16927. case Engine.TEXTUREFORMAT_ALPHA:
  16928. return this._gl.ALPHA;
  16929. }
  16930. }
  16931. return this._gl.RGBA;
  16932. };
  16933. ;
  16934. /** @hidden */
  16935. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16936. if (type === Engine.TEXTURETYPE_FLOAT) {
  16937. return this._gl.RGBA32F;
  16938. }
  16939. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16940. return this._gl.RGBA16F;
  16941. }
  16942. return this._gl.RGBA8;
  16943. };
  16944. ;
  16945. /** @hidden */
  16946. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  16947. var _this = this;
  16948. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  16949. this._activeRequests.push(request);
  16950. request.onCompleteObservable.add(function (request) {
  16951. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  16952. });
  16953. return request;
  16954. };
  16955. /** @hidden */
  16956. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  16957. var _this = this;
  16958. return new Promise(function (resolve, reject) {
  16959. _this._loadFile(url, function (data) {
  16960. resolve(data);
  16961. }, undefined, database, useArrayBuffer, function (request, exception) {
  16962. reject(exception);
  16963. });
  16964. });
  16965. };
  16966. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  16967. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  16968. var onload = function (data) {
  16969. loadedFiles[index] = data;
  16970. loadedFiles._internalCount++;
  16971. if (loadedFiles._internalCount === 6) {
  16972. onfinish(loadedFiles);
  16973. }
  16974. };
  16975. var onerror = function (request, exception) {
  16976. if (onErrorCallBack && request) {
  16977. onErrorCallBack(request.status + " " + request.statusText, exception);
  16978. }
  16979. };
  16980. this._loadFile(url, onload, undefined, undefined, true, onerror);
  16981. };
  16982. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  16983. if (onError === void 0) { onError = null; }
  16984. var loadedFiles = [];
  16985. loadedFiles._internalCount = 0;
  16986. for (var index = 0; index < 6; index++) {
  16987. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  16988. }
  16989. };
  16990. // Statics
  16991. /**
  16992. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  16993. * @returns true if the engine can be created
  16994. * @ignorenaming
  16995. */
  16996. Engine.isSupported = function () {
  16997. try {
  16998. var tempcanvas = document.createElement("canvas");
  16999. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17000. return gl != null && !!window.WebGLRenderingContext;
  17001. }
  17002. catch (e) {
  17003. return false;
  17004. }
  17005. };
  17006. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17007. Engine.ExceptionList = [
  17008. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17009. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17010. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17011. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17012. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17013. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17014. ];
  17015. /** Gets the list of created engines */
  17016. Engine.Instances = new Array();
  17017. /**
  17018. * Hidden
  17019. */
  17020. Engine._TextureLoaders = [];
  17021. // Const statics
  17022. /** Defines that alpha blending is disabled */
  17023. Engine.ALPHA_DISABLE = 0;
  17024. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17025. Engine.ALPHA_ADD = 1;
  17026. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17027. Engine.ALPHA_COMBINE = 2;
  17028. /** Defines that alpha blending to DEST - SRC * DEST */
  17029. Engine.ALPHA_SUBTRACT = 3;
  17030. /** Defines that alpha blending to SRC * DEST */
  17031. Engine.ALPHA_MULTIPLY = 4;
  17032. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17033. Engine.ALPHA_MAXIMIZED = 5;
  17034. /** Defines that alpha blending to SRC + DEST */
  17035. Engine.ALPHA_ONEONE = 6;
  17036. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17037. Engine.ALPHA_PREMULTIPLIED = 7;
  17038. /**
  17039. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17040. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17041. */
  17042. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17043. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17044. Engine.ALPHA_INTERPOLATE = 9;
  17045. /**
  17046. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17047. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17048. */
  17049. Engine.ALPHA_SCREENMODE = 10;
  17050. /** Defines that the ressource is not delayed*/
  17051. Engine.DELAYLOADSTATE_NONE = 0;
  17052. /** Defines that the ressource was successfully delay loaded */
  17053. Engine.DELAYLOADSTATE_LOADED = 1;
  17054. /** Defines that the ressource is currently delay loading */
  17055. Engine.DELAYLOADSTATE_LOADING = 2;
  17056. /** Defines that the ressource is delayed and has not started loading */
  17057. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17058. // Depht or Stencil test Constants.
  17059. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17060. Engine.NEVER = 0x0200;
  17061. /** 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 */
  17062. Engine.ALWAYS = 0x0207;
  17063. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17064. Engine.LESS = 0x0201;
  17065. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17066. Engine.EQUAL = 0x0202;
  17067. /** 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 */
  17068. Engine.LEQUAL = 0x0203;
  17069. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17070. Engine.GREATER = 0x0204;
  17071. /** 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 */
  17072. Engine.GEQUAL = 0x0206;
  17073. /** 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 */
  17074. Engine.NOTEQUAL = 0x0205;
  17075. // Stencil Actions Constants.
  17076. /** Passed to stencilOperation to specify that stencil value must be kept */
  17077. Engine.KEEP = 0x1E00;
  17078. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17079. Engine.REPLACE = 0x1E01;
  17080. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17081. Engine.INCR = 0x1E02;
  17082. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17083. Engine.DECR = 0x1E03;
  17084. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17085. Engine.INVERT = 0x150A;
  17086. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17087. Engine.INCR_WRAP = 0x8507;
  17088. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17089. Engine.DECR_WRAP = 0x8508;
  17090. /** Texture is not repeating outside of 0..1 UVs */
  17091. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17092. /** Texture is repeating outside of 0..1 UVs */
  17093. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17094. /** Texture is repeating and mirrored */
  17095. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17096. /** ALPHA */
  17097. Engine.TEXTUREFORMAT_ALPHA = 0;
  17098. /** LUMINANCE */
  17099. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17100. /** LUMINANCE_ALPHA */
  17101. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17102. /** RGB */
  17103. Engine.TEXTUREFORMAT_RGB = 4;
  17104. /** RGBA */
  17105. Engine.TEXTUREFORMAT_RGBA = 5;
  17106. /** R */
  17107. Engine.TEXTUREFORMAT_R = 6;
  17108. /** RG */
  17109. Engine.TEXTUREFORMAT_RG = 7;
  17110. /** UNSIGNED_INT */
  17111. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17112. /** FLOAT */
  17113. Engine.TEXTURETYPE_FLOAT = 1;
  17114. /** HALF_FLOAT */
  17115. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17116. /** nearest is mag = nearest and min = nearest and mip = linear */
  17117. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17118. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17119. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17120. /** Trilinear is mag = linear and min = linear and mip = linear */
  17121. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17122. /** nearest is mag = nearest and min = nearest and mip = linear */
  17123. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17124. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17125. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17126. /** Trilinear is mag = linear and min = linear and mip = linear */
  17127. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17128. /** mag = nearest and min = nearest and mip = nearest */
  17129. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17130. /** mag = nearest and min = linear and mip = nearest */
  17131. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17132. /** mag = nearest and min = linear and mip = linear */
  17133. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17134. /** mag = nearest and min = linear and mip = none */
  17135. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17136. /** mag = nearest and min = nearest and mip = none */
  17137. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17138. /** mag = linear and min = nearest and mip = nearest */
  17139. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17140. /** mag = linear and min = nearest and mip = linear */
  17141. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17142. /** mag = linear and min = linear and mip = none */
  17143. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17144. /** mag = linear and min = nearest and mip = none */
  17145. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17146. /** Explicit coordinates mode */
  17147. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17148. /** Spherical coordinates mode */
  17149. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17150. /** Planar coordinates mode */
  17151. Engine.TEXTURE_PLANAR_MODE = 2;
  17152. /** Cubic coordinates mode */
  17153. Engine.TEXTURE_CUBIC_MODE = 3;
  17154. /** Projection coordinates mode */
  17155. Engine.TEXTURE_PROJECTION_MODE = 4;
  17156. /** Skybox coordinates mode */
  17157. Engine.TEXTURE_SKYBOX_MODE = 5;
  17158. /** Inverse Cubic coordinates mode */
  17159. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17160. /** Equirectangular coordinates mode */
  17161. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17162. /** Equirectangular Fixed coordinates mode */
  17163. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17164. /** Equirectangular Fixed Mirrored coordinates mode */
  17165. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17166. // Texture rescaling mode
  17167. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17168. Engine.SCALEMODE_FLOOR = 1;
  17169. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17170. Engine.SCALEMODE_NEAREST = 2;
  17171. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17172. Engine.SCALEMODE_CEILING = 3;
  17173. // Updatable statics so stick with vars here
  17174. /**
  17175. * Gets or sets the epsilon value used by collision engine
  17176. */
  17177. Engine.CollisionsEpsilon = 0.001;
  17178. /**
  17179. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17180. */
  17181. Engine.CodeRepository = "src/";
  17182. /**
  17183. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17184. */
  17185. Engine.ShadersRepository = "src/Shaders/";
  17186. return Engine;
  17187. }());
  17188. BABYLON.Engine = Engine;
  17189. })(BABYLON || (BABYLON = {}));
  17190. //# sourceMappingURL=babylon.engine.js.map
  17191. var BABYLON;
  17192. (function (BABYLON) {
  17193. /**
  17194. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17195. */
  17196. var Node = /** @class */ (function () {
  17197. /**
  17198. * Creates a new Node
  17199. * @param {string} name - the name and id to be given to this node
  17200. * @param {BABYLON.Scene} the scene this node will be added to
  17201. */
  17202. function Node(name, scene) {
  17203. if (scene === void 0) { scene = null; }
  17204. /**
  17205. * Gets or sets a string used to store user defined state for the node
  17206. */
  17207. this.state = "";
  17208. /**
  17209. * Gets or sets an object used to store user defined information for the node
  17210. */
  17211. this.metadata = null;
  17212. /**
  17213. * Gets or sets a boolean used to define if the node must be serialized
  17214. */
  17215. this.doNotSerialize = false;
  17216. /** @hidden */
  17217. this._isDisposed = false;
  17218. /**
  17219. * Gets a list of Animations associated with the node
  17220. */
  17221. this.animations = new Array();
  17222. this._ranges = {};
  17223. this._isEnabled = true;
  17224. this._isReady = true;
  17225. /** @hidden */
  17226. this._currentRenderId = -1;
  17227. this._parentRenderId = -1;
  17228. this._childRenderId = -1;
  17229. this._animationPropertiesOverride = null;
  17230. /**
  17231. * An event triggered when the mesh is disposed
  17232. */
  17233. this.onDisposeObservable = new BABYLON.Observable();
  17234. // Behaviors
  17235. this._behaviors = new Array();
  17236. this.name = name;
  17237. this.id = name;
  17238. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17239. this.uniqueId = this._scene.getUniqueId();
  17240. this._initCache();
  17241. }
  17242. /**
  17243. * Add a new node constructor
  17244. * @param type defines the type name of the node to construct
  17245. * @param constructorFunc defines the constructor function
  17246. */
  17247. Node.AddNodeConstructor = function (type, constructorFunc) {
  17248. this._NodeConstructors[type] = constructorFunc;
  17249. };
  17250. /**
  17251. * Returns a node constructor based on type name
  17252. * @param type defines the type name
  17253. * @param name defines the new node name
  17254. * @param scene defines the hosting scene
  17255. * @param options defines optional options to transmit to constructors
  17256. * @returns the new constructor or null
  17257. */
  17258. Node.Construct = function (type, name, scene, options) {
  17259. var constructorFunc = this._NodeConstructors[type];
  17260. if (!constructorFunc) {
  17261. return null;
  17262. }
  17263. return constructorFunc(name, scene, options);
  17264. };
  17265. /**
  17266. * Gets a boolean indicating if the node has been disposed
  17267. * @returns true if the node was disposed
  17268. */
  17269. Node.prototype.isDisposed = function () {
  17270. return this._isDisposed;
  17271. };
  17272. Object.defineProperty(Node.prototype, "parent", {
  17273. get: function () {
  17274. return this._parentNode;
  17275. },
  17276. /**
  17277. * Gets or sets the parent of the node
  17278. */
  17279. set: function (parent) {
  17280. if (this._parentNode === parent) {
  17281. return;
  17282. }
  17283. // Remove self from list of children of parent
  17284. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17285. var index = this._parentNode._children.indexOf(this);
  17286. if (index !== -1) {
  17287. this._parentNode._children.splice(index, 1);
  17288. }
  17289. }
  17290. // Store new parent
  17291. this._parentNode = parent;
  17292. // Add as child to new parent
  17293. if (this._parentNode) {
  17294. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17295. this._parentNode._children = new Array();
  17296. }
  17297. this._parentNode._children.push(this);
  17298. }
  17299. },
  17300. enumerable: true,
  17301. configurable: true
  17302. });
  17303. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17304. /**
  17305. * Gets or sets the animation properties override
  17306. */
  17307. get: function () {
  17308. if (!this._animationPropertiesOverride) {
  17309. return this._scene.animationPropertiesOverride;
  17310. }
  17311. return this._animationPropertiesOverride;
  17312. },
  17313. set: function (value) {
  17314. this._animationPropertiesOverride = value;
  17315. },
  17316. enumerable: true,
  17317. configurable: true
  17318. });
  17319. /**
  17320. * Gets a string idenfifying the name of the class
  17321. * @returns "Node" string
  17322. */
  17323. Node.prototype.getClassName = function () {
  17324. return "Node";
  17325. };
  17326. Object.defineProperty(Node.prototype, "onDispose", {
  17327. /**
  17328. * Sets a callback that will be raised when the node will be disposed
  17329. */
  17330. set: function (callback) {
  17331. if (this._onDisposeObserver) {
  17332. this.onDisposeObservable.remove(this._onDisposeObserver);
  17333. }
  17334. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17335. },
  17336. enumerable: true,
  17337. configurable: true
  17338. });
  17339. /**
  17340. * Gets the scene of the node
  17341. * @returns a {BABYLON.Scene}
  17342. */
  17343. Node.prototype.getScene = function () {
  17344. return this._scene;
  17345. };
  17346. /**
  17347. * Gets the engine of the node
  17348. * @returns a {BABYLON.Engine}
  17349. */
  17350. Node.prototype.getEngine = function () {
  17351. return this._scene.getEngine();
  17352. };
  17353. /**
  17354. * Attach a behavior to the node
  17355. * @see http://doc.babylonjs.com/features/behaviour
  17356. * @param behavior defines the behavior to attach
  17357. * @returns the current Node
  17358. */
  17359. Node.prototype.addBehavior = function (behavior) {
  17360. var _this = this;
  17361. var index = this._behaviors.indexOf(behavior);
  17362. if (index !== -1) {
  17363. return this;
  17364. }
  17365. behavior.init();
  17366. if (this._scene.isLoading) {
  17367. // We defer the attach when the scene will be loaded
  17368. this._scene.onDataLoadedObservable.addOnce(function () {
  17369. behavior.attach(_this);
  17370. });
  17371. }
  17372. else {
  17373. behavior.attach(this);
  17374. }
  17375. this._behaviors.push(behavior);
  17376. return this;
  17377. };
  17378. /**
  17379. * Remove an attached behavior
  17380. * @see http://doc.babylonjs.com/features/behaviour
  17381. * @param behavior defines the behavior to attach
  17382. * @returns the current Node
  17383. */
  17384. Node.prototype.removeBehavior = function (behavior) {
  17385. var index = this._behaviors.indexOf(behavior);
  17386. if (index === -1) {
  17387. return this;
  17388. }
  17389. this._behaviors[index].detach();
  17390. this._behaviors.splice(index, 1);
  17391. return this;
  17392. };
  17393. Object.defineProperty(Node.prototype, "behaviors", {
  17394. /**
  17395. * Gets the list of attached behaviors
  17396. * @see http://doc.babylonjs.com/features/behaviour
  17397. */
  17398. get: function () {
  17399. return this._behaviors;
  17400. },
  17401. enumerable: true,
  17402. configurable: true
  17403. });
  17404. /**
  17405. * Gets an attached behavior by name
  17406. * @param name defines the name of the behavior to look for
  17407. * @see http://doc.babylonjs.com/features/behaviour
  17408. * @returns null if behavior was not found else the requested behavior
  17409. */
  17410. Node.prototype.getBehaviorByName = function (name) {
  17411. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17412. var behavior = _a[_i];
  17413. if (behavior.name === name) {
  17414. return behavior;
  17415. }
  17416. }
  17417. return null;
  17418. };
  17419. /**
  17420. * Returns the world matrix of the node
  17421. * @returns a matrix containing the node's world matrix
  17422. */
  17423. Node.prototype.getWorldMatrix = function () {
  17424. return BABYLON.Matrix.Identity();
  17425. };
  17426. /** @hidden */
  17427. Node.prototype._getWorldMatrixDeterminant = function () {
  17428. return 1;
  17429. };
  17430. // override it in derived class if you add new variables to the cache
  17431. // and call the parent class method
  17432. /** @hidden */
  17433. Node.prototype._initCache = function () {
  17434. this._cache = {};
  17435. this._cache.parent = undefined;
  17436. };
  17437. /** @hidden */
  17438. Node.prototype.updateCache = function (force) {
  17439. if (!force && this.isSynchronized())
  17440. return;
  17441. this._cache.parent = this.parent;
  17442. this._updateCache();
  17443. };
  17444. // override it in derived class if you add new variables to the cache
  17445. // and call the parent class method if !ignoreParentClass
  17446. /** @hidden */
  17447. Node.prototype._updateCache = function (ignoreParentClass) {
  17448. };
  17449. // override it in derived class if you add new variables to the cache
  17450. /** @hidden */
  17451. Node.prototype._isSynchronized = function () {
  17452. return true;
  17453. };
  17454. /** @hidden */
  17455. Node.prototype._markSyncedWithParent = function () {
  17456. if (this.parent) {
  17457. this._parentRenderId = this.parent._childRenderId;
  17458. }
  17459. };
  17460. /** @hidden */
  17461. Node.prototype.isSynchronizedWithParent = function () {
  17462. if (!this.parent) {
  17463. return true;
  17464. }
  17465. if (this._parentRenderId !== this.parent._childRenderId) {
  17466. return false;
  17467. }
  17468. return this.parent.isSynchronized();
  17469. };
  17470. /** @hidden */
  17471. Node.prototype.isSynchronized = function (updateCache) {
  17472. var check = this.hasNewParent();
  17473. check = check || !this.isSynchronizedWithParent();
  17474. check = check || !this._isSynchronized();
  17475. if (updateCache)
  17476. this.updateCache(true);
  17477. return !check;
  17478. };
  17479. /** @hidden */
  17480. Node.prototype.hasNewParent = function (update) {
  17481. if (this._cache.parent === this.parent)
  17482. return false;
  17483. if (update)
  17484. this._cache.parent = this.parent;
  17485. return true;
  17486. };
  17487. /**
  17488. * Is this node ready to be used/rendered
  17489. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17490. * @return true if the node is ready
  17491. */
  17492. Node.prototype.isReady = function (completeCheck) {
  17493. if (completeCheck === void 0) { completeCheck = false; }
  17494. return this._isReady;
  17495. };
  17496. /**
  17497. * Is this node enabled?
  17498. * 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
  17499. * @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
  17500. * @return whether this node (and its parent) is enabled
  17501. */
  17502. Node.prototype.isEnabled = function (checkAncestors) {
  17503. if (checkAncestors === void 0) { checkAncestors = true; }
  17504. if (checkAncestors === false) {
  17505. return this._isEnabled;
  17506. }
  17507. if (this._isEnabled === false) {
  17508. return false;
  17509. }
  17510. if (this.parent !== undefined && this.parent !== null) {
  17511. return this.parent.isEnabled(checkAncestors);
  17512. }
  17513. return true;
  17514. };
  17515. /**
  17516. * Set the enabled state of this node
  17517. * @param value defines the new enabled state
  17518. */
  17519. Node.prototype.setEnabled = function (value) {
  17520. this._isEnabled = value;
  17521. };
  17522. /**
  17523. * Is this node a descendant of the given node?
  17524. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17525. * @param ancestor defines the parent node to inspect
  17526. * @returns a boolean indicating if this node is a descendant of the given node
  17527. */
  17528. Node.prototype.isDescendantOf = function (ancestor) {
  17529. if (this.parent) {
  17530. if (this.parent === ancestor) {
  17531. return true;
  17532. }
  17533. return this.parent.isDescendantOf(ancestor);
  17534. }
  17535. return false;
  17536. };
  17537. /** @hidden */
  17538. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17539. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17540. if (!this._children) {
  17541. return;
  17542. }
  17543. for (var index = 0; index < this._children.length; index++) {
  17544. var item = this._children[index];
  17545. if (!predicate || predicate(item)) {
  17546. results.push(item);
  17547. }
  17548. if (!directDescendantsOnly) {
  17549. item._getDescendants(results, false, predicate);
  17550. }
  17551. }
  17552. };
  17553. /**
  17554. * Will return all nodes that have this node as ascendant
  17555. * @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
  17556. * @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
  17557. * @return all children nodes of all types
  17558. */
  17559. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17560. var results = new Array();
  17561. this._getDescendants(results, directDescendantsOnly, predicate);
  17562. return results;
  17563. };
  17564. /**
  17565. * Get all child-meshes of this node
  17566. * @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
  17567. * @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
  17568. * @returns an array of {BABYLON.AbstractMesh}
  17569. */
  17570. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17571. var results = [];
  17572. this._getDescendants(results, directDescendantsOnly, function (node) {
  17573. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17574. });
  17575. return results;
  17576. };
  17577. /**
  17578. * Get all child-transformNodes of this node
  17579. * @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
  17580. * @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
  17581. * @returns an array of {BABYLON.TransformNode}
  17582. */
  17583. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17584. var results = [];
  17585. this._getDescendants(results, directDescendantsOnly, function (node) {
  17586. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17587. });
  17588. return results;
  17589. };
  17590. /**
  17591. * Get all direct children of this node
  17592. * @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
  17593. * @returns an array of {BABYLON.Node}
  17594. */
  17595. Node.prototype.getChildren = function (predicate) {
  17596. return this.getDescendants(true, predicate);
  17597. };
  17598. /** @hidden */
  17599. Node.prototype._setReady = function (state) {
  17600. if (state === this._isReady) {
  17601. return;
  17602. }
  17603. if (!state) {
  17604. this._isReady = false;
  17605. return;
  17606. }
  17607. if (this.onReady) {
  17608. this.onReady(this);
  17609. }
  17610. this._isReady = true;
  17611. };
  17612. /**
  17613. * Get an animation by name
  17614. * @param name defines the name of the animation to look for
  17615. * @returns null if not found else the requested animation
  17616. */
  17617. Node.prototype.getAnimationByName = function (name) {
  17618. for (var i = 0; i < this.animations.length; i++) {
  17619. var animation = this.animations[i];
  17620. if (animation.name === name) {
  17621. return animation;
  17622. }
  17623. }
  17624. return null;
  17625. };
  17626. /**
  17627. * Creates an animation range for this node
  17628. * @param name defines the name of the range
  17629. * @param from defines the starting key
  17630. * @param to defines the end key
  17631. */
  17632. Node.prototype.createAnimationRange = function (name, from, to) {
  17633. // check name not already in use
  17634. if (!this._ranges[name]) {
  17635. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17636. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17637. if (this.animations[i]) {
  17638. this.animations[i].createRange(name, from, to);
  17639. }
  17640. }
  17641. }
  17642. };
  17643. /**
  17644. * Delete a specific animation range
  17645. * @param name defines the name of the range to delete
  17646. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17647. */
  17648. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17649. if (deleteFrames === void 0) { deleteFrames = true; }
  17650. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17651. if (this.animations[i]) {
  17652. this.animations[i].deleteRange(name, deleteFrames);
  17653. }
  17654. }
  17655. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17656. };
  17657. /**
  17658. * Get an animation range by name
  17659. * @param name defines the name of the animation range to look for
  17660. * @returns null if not found else the requested animation range
  17661. */
  17662. Node.prototype.getAnimationRange = function (name) {
  17663. return this._ranges[name];
  17664. };
  17665. /**
  17666. * Will start the animation sequence
  17667. * @param name defines the range frames for animation sequence
  17668. * @param loop defines if the animation should loop (false by default)
  17669. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17670. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17671. * @returns the object created for this animation. If range does not exist, it will return null
  17672. */
  17673. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17674. var range = this.getAnimationRange(name);
  17675. if (!range) {
  17676. return null;
  17677. }
  17678. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17679. };
  17680. /**
  17681. * Serialize animation ranges into a JSON compatible object
  17682. * @returns serialization object
  17683. */
  17684. Node.prototype.serializeAnimationRanges = function () {
  17685. var serializationRanges = [];
  17686. for (var name in this._ranges) {
  17687. var localRange = this._ranges[name];
  17688. if (!localRange) {
  17689. continue;
  17690. }
  17691. var range = {};
  17692. range.name = name;
  17693. range.from = localRange.from;
  17694. range.to = localRange.to;
  17695. serializationRanges.push(range);
  17696. }
  17697. return serializationRanges;
  17698. };
  17699. /**
  17700. * Computes the world matrix of the node
  17701. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17702. * @returns the world matrix
  17703. */
  17704. Node.prototype.computeWorldMatrix = function (force) {
  17705. return BABYLON.Matrix.Identity();
  17706. };
  17707. /**
  17708. * Releases resources associated with this node.
  17709. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17710. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17711. */
  17712. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17713. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17714. if (!doNotRecurse) {
  17715. var nodes = this.getDescendants(true);
  17716. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17717. var node = nodes_1[_i];
  17718. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17719. }
  17720. }
  17721. else {
  17722. var transformNodes = this.getChildTransformNodes(true);
  17723. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17724. var transformNode = transformNodes_1[_a];
  17725. transformNode.parent = null;
  17726. transformNode.computeWorldMatrix(true);
  17727. }
  17728. }
  17729. this.parent = null;
  17730. // Callback
  17731. this.onDisposeObservable.notifyObservers(this);
  17732. this.onDisposeObservable.clear();
  17733. // Behaviors
  17734. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17735. var behavior = _c[_b];
  17736. behavior.detach();
  17737. }
  17738. this._behaviors = [];
  17739. this._isDisposed = true;
  17740. };
  17741. /**
  17742. * Parse animation range data from a serialization object and store them into a given node
  17743. * @param node defines where to store the animation ranges
  17744. * @param parsedNode defines the serialization object to read data from
  17745. * @param scene defines the hosting scene
  17746. */
  17747. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17748. if (parsedNode.ranges) {
  17749. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17750. var data = parsedNode.ranges[index];
  17751. node.createAnimationRange(data.name, data.from, data.to);
  17752. }
  17753. }
  17754. };
  17755. Node._NodeConstructors = {};
  17756. __decorate([
  17757. BABYLON.serialize()
  17758. ], Node.prototype, "name", void 0);
  17759. __decorate([
  17760. BABYLON.serialize()
  17761. ], Node.prototype, "id", void 0);
  17762. __decorate([
  17763. BABYLON.serialize()
  17764. ], Node.prototype, "uniqueId", void 0);
  17765. __decorate([
  17766. BABYLON.serialize()
  17767. ], Node.prototype, "state", void 0);
  17768. __decorate([
  17769. BABYLON.serialize()
  17770. ], Node.prototype, "metadata", void 0);
  17771. return Node;
  17772. }());
  17773. BABYLON.Node = Node;
  17774. })(BABYLON || (BABYLON = {}));
  17775. //# sourceMappingURL=babylon.node.js.map
  17776. var BABYLON;
  17777. (function (BABYLON) {
  17778. var BoundingSphere = /** @class */ (function () {
  17779. /**
  17780. * Creates a new bounding sphere
  17781. * @param min defines the minimum vector (in local space)
  17782. * @param max defines the maximum vector (in local space)
  17783. */
  17784. function BoundingSphere(min, max) {
  17785. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17786. this.reConstruct(min, max);
  17787. }
  17788. /**
  17789. * Recreates the entire bounding sphere from scratch
  17790. * @param min defines the new minimum vector (in local space)
  17791. * @param max defines the new maximum vector (in local space)
  17792. */
  17793. BoundingSphere.prototype.reConstruct = function (min, max) {
  17794. this.minimum = min.clone();
  17795. this.maximum = max.clone();
  17796. var distance = BABYLON.Vector3.Distance(min, max);
  17797. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17798. this.radius = distance * 0.5;
  17799. this.centerWorld = BABYLON.Vector3.Zero();
  17800. this._update(BABYLON.Matrix.Identity());
  17801. };
  17802. /**
  17803. * Scale the current bounding sphere by applying a scale factor
  17804. * @param factor defines the scale factor to apply
  17805. * @returns the current bounding box
  17806. */
  17807. BoundingSphere.prototype.scale = function (factor) {
  17808. var newRadius = this.radius * factor;
  17809. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  17810. var min = this.center.subtract(newRadiusVector);
  17811. var max = this.center.add(newRadiusVector);
  17812. this.reConstruct(min, max);
  17813. return this;
  17814. };
  17815. // Methods
  17816. BoundingSphere.prototype._update = function (world) {
  17817. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17818. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17819. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17820. };
  17821. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17822. for (var i = 0; i < 6; i++) {
  17823. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17824. return false;
  17825. }
  17826. return true;
  17827. };
  17828. BoundingSphere.prototype.intersectsPoint = function (point) {
  17829. var x = this.centerWorld.x - point.x;
  17830. var y = this.centerWorld.y - point.y;
  17831. var z = this.centerWorld.z - point.z;
  17832. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17833. if (this.radiusWorld < distance)
  17834. return false;
  17835. return true;
  17836. };
  17837. // Statics
  17838. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17839. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17840. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17841. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17842. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17843. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17844. return false;
  17845. return true;
  17846. };
  17847. return BoundingSphere;
  17848. }());
  17849. BABYLON.BoundingSphere = BoundingSphere;
  17850. })(BABYLON || (BABYLON = {}));
  17851. //# sourceMappingURL=babylon.boundingSphere.js.map
  17852. var BABYLON;
  17853. (function (BABYLON) {
  17854. var BoundingBox = /** @class */ (function () {
  17855. /**
  17856. * Creates a new bounding box
  17857. * @param min defines the minimum vector (in local space)
  17858. * @param max defines the maximum vector (in local space)
  17859. */
  17860. function BoundingBox(min, max) {
  17861. this.vectorsWorld = new Array();
  17862. this.reConstruct(min, max);
  17863. }
  17864. // Methods
  17865. /**
  17866. * Recreates the entire bounding box from scratch
  17867. * @param min defines the new minimum vector (in local space)
  17868. * @param max defines the new maximum vector (in local space)
  17869. */
  17870. BoundingBox.prototype.reConstruct = function (min, max) {
  17871. this.minimum = min.clone();
  17872. this.maximum = max.clone();
  17873. // Bounding vectors
  17874. this.vectors = new Array();
  17875. this.vectors.push(this.minimum.clone());
  17876. this.vectors.push(this.maximum.clone());
  17877. this.vectors.push(this.minimum.clone());
  17878. this.vectors[2].x = this.maximum.x;
  17879. this.vectors.push(this.minimum.clone());
  17880. this.vectors[3].y = this.maximum.y;
  17881. this.vectors.push(this.minimum.clone());
  17882. this.vectors[4].z = this.maximum.z;
  17883. this.vectors.push(this.maximum.clone());
  17884. this.vectors[5].z = this.minimum.z;
  17885. this.vectors.push(this.maximum.clone());
  17886. this.vectors[6].x = this.minimum.x;
  17887. this.vectors.push(this.maximum.clone());
  17888. this.vectors[7].y = this.minimum.y;
  17889. // OBB
  17890. this.center = this.maximum.add(this.minimum).scale(0.5);
  17891. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17892. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17893. // World
  17894. for (var index = 0; index < this.vectors.length; index++) {
  17895. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17896. }
  17897. this.minimumWorld = BABYLON.Vector3.Zero();
  17898. this.maximumWorld = BABYLON.Vector3.Zero();
  17899. this.centerWorld = BABYLON.Vector3.Zero();
  17900. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17901. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17902. };
  17903. /**
  17904. * Scale the current bounding box by applying a scale factor
  17905. * @param factor defines the scale factor to apply
  17906. * @returns the current bounding box
  17907. */
  17908. BoundingBox.prototype.scale = function (factor) {
  17909. var diff = this.maximum.subtract(this.minimum);
  17910. var distance = diff.length() * factor;
  17911. diff.normalize();
  17912. var newRadius = diff.scale(distance / 2);
  17913. var min = this.center.subtract(newRadius);
  17914. var max = this.center.add(newRadius);
  17915. this.reConstruct(min, max);
  17916. return this;
  17917. };
  17918. BoundingBox.prototype.getWorldMatrix = function () {
  17919. return this._worldMatrix;
  17920. };
  17921. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17922. this._worldMatrix.copyFrom(matrix);
  17923. return this;
  17924. };
  17925. BoundingBox.prototype._update = function (world) {
  17926. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17927. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17928. for (var index = 0; index < this.vectors.length; index++) {
  17929. var v = this.vectorsWorld[index];
  17930. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17931. if (v.x < this.minimumWorld.x)
  17932. this.minimumWorld.x = v.x;
  17933. if (v.y < this.minimumWorld.y)
  17934. this.minimumWorld.y = v.y;
  17935. if (v.z < this.minimumWorld.z)
  17936. this.minimumWorld.z = v.z;
  17937. if (v.x > this.maximumWorld.x)
  17938. this.maximumWorld.x = v.x;
  17939. if (v.y > this.maximumWorld.y)
  17940. this.maximumWorld.y = v.y;
  17941. if (v.z > this.maximumWorld.z)
  17942. this.maximumWorld.z = v.z;
  17943. }
  17944. // Extend
  17945. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17946. this.extendSizeWorld.scaleInPlace(0.5);
  17947. // OBB
  17948. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17949. this.centerWorld.scaleInPlace(0.5);
  17950. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17951. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17952. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17953. this._worldMatrix = world;
  17954. };
  17955. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17956. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17957. };
  17958. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17959. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17960. };
  17961. BoundingBox.prototype.intersectsPoint = function (point) {
  17962. var delta = -BABYLON.Epsilon;
  17963. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17964. return false;
  17965. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17966. return false;
  17967. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17968. return false;
  17969. return true;
  17970. };
  17971. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17972. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17973. };
  17974. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17975. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17976. return false;
  17977. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17978. return false;
  17979. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17980. return false;
  17981. return true;
  17982. };
  17983. // Statics
  17984. BoundingBox.Intersects = function (box0, box1) {
  17985. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17986. return false;
  17987. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17988. return false;
  17989. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17990. return false;
  17991. return true;
  17992. };
  17993. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17994. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17995. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17996. return (num <= (sphereRadius * sphereRadius));
  17997. };
  17998. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17999. for (var p = 0; p < 6; p++) {
  18000. for (var i = 0; i < 8; i++) {
  18001. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18002. return false;
  18003. }
  18004. }
  18005. }
  18006. return true;
  18007. };
  18008. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18009. for (var p = 0; p < 6; p++) {
  18010. var inCount = 8;
  18011. for (var i = 0; i < 8; i++) {
  18012. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18013. --inCount;
  18014. }
  18015. else {
  18016. break;
  18017. }
  18018. }
  18019. if (inCount === 0)
  18020. return false;
  18021. }
  18022. return true;
  18023. };
  18024. return BoundingBox;
  18025. }());
  18026. BABYLON.BoundingBox = BoundingBox;
  18027. })(BABYLON || (BABYLON = {}));
  18028. //# sourceMappingURL=babylon.boundingBox.js.map
  18029. var BABYLON;
  18030. (function (BABYLON) {
  18031. var computeBoxExtents = function (axis, box) {
  18032. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18033. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18034. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18035. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18036. var r = r0 + r1 + r2;
  18037. return {
  18038. min: p - r,
  18039. max: p + r
  18040. };
  18041. };
  18042. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18043. var axisOverlap = function (axis, box0, box1) {
  18044. var result0 = computeBoxExtents(axis, box0);
  18045. var result1 = computeBoxExtents(axis, box1);
  18046. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18047. };
  18048. var BoundingInfo = /** @class */ (function () {
  18049. function BoundingInfo(minimum, maximum) {
  18050. this.minimum = minimum;
  18051. this.maximum = maximum;
  18052. this._isLocked = false;
  18053. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18054. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18055. }
  18056. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18057. get: function () {
  18058. return this._isLocked;
  18059. },
  18060. set: function (value) {
  18061. this._isLocked = value;
  18062. },
  18063. enumerable: true,
  18064. configurable: true
  18065. });
  18066. // Methods
  18067. BoundingInfo.prototype.update = function (world) {
  18068. if (this._isLocked) {
  18069. return;
  18070. }
  18071. this.boundingBox._update(world);
  18072. this.boundingSphere._update(world);
  18073. };
  18074. /**
  18075. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18076. * @param center New center of the bounding info
  18077. * @param extend New extend of the bounding info
  18078. */
  18079. BoundingInfo.prototype.centerOn = function (center, extend) {
  18080. this.minimum = center.subtract(extend);
  18081. this.maximum = center.add(extend);
  18082. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18083. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18084. return this;
  18085. };
  18086. /**
  18087. * Scale the current bounding info by applying a scale factor
  18088. * @param factor defines the scale factor to apply
  18089. * @returns the current bounding info
  18090. */
  18091. BoundingInfo.prototype.scale = function (factor) {
  18092. this.boundingBox.scale(factor);
  18093. this.boundingSphere.scale(factor);
  18094. return this;
  18095. };
  18096. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18097. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18098. return false;
  18099. return this.boundingBox.isInFrustum(frustumPlanes);
  18100. };
  18101. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18102. /**
  18103. * Gets the world distance between the min and max points of the bounding box
  18104. */
  18105. get: function () {
  18106. var boundingBox = this.boundingBox;
  18107. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18108. return size.length();
  18109. },
  18110. enumerable: true,
  18111. configurable: true
  18112. });
  18113. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18114. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18115. };
  18116. BoundingInfo.prototype._checkCollision = function (collider) {
  18117. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18118. };
  18119. BoundingInfo.prototype.intersectsPoint = function (point) {
  18120. if (!this.boundingSphere.centerWorld) {
  18121. return false;
  18122. }
  18123. if (!this.boundingSphere.intersectsPoint(point)) {
  18124. return false;
  18125. }
  18126. if (!this.boundingBox.intersectsPoint(point)) {
  18127. return false;
  18128. }
  18129. return true;
  18130. };
  18131. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18132. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18133. return false;
  18134. }
  18135. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18136. return false;
  18137. }
  18138. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18139. return false;
  18140. }
  18141. if (!precise) {
  18142. return true;
  18143. }
  18144. var box0 = this.boundingBox;
  18145. var box1 = boundingInfo.boundingBox;
  18146. if (!axisOverlap(box0.directions[0], box0, box1))
  18147. return false;
  18148. if (!axisOverlap(box0.directions[1], box0, box1))
  18149. return false;
  18150. if (!axisOverlap(box0.directions[2], box0, box1))
  18151. return false;
  18152. if (!axisOverlap(box1.directions[0], box0, box1))
  18153. return false;
  18154. if (!axisOverlap(box1.directions[1], box0, box1))
  18155. return false;
  18156. if (!axisOverlap(box1.directions[2], box0, box1))
  18157. return false;
  18158. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18159. return false;
  18160. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18161. return false;
  18162. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18163. return false;
  18164. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18165. return false;
  18166. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18167. return false;
  18168. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18169. return false;
  18170. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18171. return false;
  18172. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18173. return false;
  18174. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18175. return false;
  18176. return true;
  18177. };
  18178. return BoundingInfo;
  18179. }());
  18180. BABYLON.BoundingInfo = BoundingInfo;
  18181. })(BABYLON || (BABYLON = {}));
  18182. //# sourceMappingURL=babylon.boundingInfo.js.map
  18183. var BABYLON;
  18184. (function (BABYLON) {
  18185. var TransformNode = /** @class */ (function (_super) {
  18186. __extends(TransformNode, _super);
  18187. function TransformNode(name, scene, isPure) {
  18188. if (scene === void 0) { scene = null; }
  18189. if (isPure === void 0) { isPure = true; }
  18190. var _this = _super.call(this, name, scene) || this;
  18191. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18192. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18193. _this._up = new BABYLON.Vector3(0, 1, 0);
  18194. _this._right = new BABYLON.Vector3(1, 0, 0);
  18195. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18196. // Properties
  18197. _this._rotation = BABYLON.Vector3.Zero();
  18198. _this._scaling = BABYLON.Vector3.One();
  18199. _this._isDirty = false;
  18200. /**
  18201. * Set the billboard mode. Default is 0.
  18202. *
  18203. * | Value | Type | Description |
  18204. * | --- | --- | --- |
  18205. * | 0 | BILLBOARDMODE_NONE | |
  18206. * | 1 | BILLBOARDMODE_X | |
  18207. * | 2 | BILLBOARDMODE_Y | |
  18208. * | 4 | BILLBOARDMODE_Z | |
  18209. * | 7 | BILLBOARDMODE_ALL | |
  18210. *
  18211. */
  18212. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18213. _this.scalingDeterminant = 1;
  18214. _this.infiniteDistance = false;
  18215. /**
  18216. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18217. * By default the system will update normals to compensate
  18218. */
  18219. _this.ignoreNonUniformScaling = false;
  18220. _this.position = BABYLON.Vector3.Zero();
  18221. _this._localWorld = BABYLON.Matrix.Zero();
  18222. _this._worldMatrix = BABYLON.Matrix.Zero();
  18223. _this._worldMatrixDeterminant = 0;
  18224. _this._absolutePosition = BABYLON.Vector3.Zero();
  18225. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18226. _this._postMultiplyPivotMatrix = false;
  18227. _this._isWorldMatrixFrozen = false;
  18228. /**
  18229. * An event triggered after the world matrix is updated
  18230. */
  18231. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18232. _this._nonUniformScaling = false;
  18233. if (isPure) {
  18234. _this.getScene().addTransformNode(_this);
  18235. }
  18236. return _this;
  18237. }
  18238. /**
  18239. * Gets a string idenfifying the name of the class
  18240. * @returns "TransformNode" string
  18241. */
  18242. TransformNode.prototype.getClassName = function () {
  18243. return "TransformNode";
  18244. };
  18245. Object.defineProperty(TransformNode.prototype, "rotation", {
  18246. /**
  18247. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18248. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18249. * Default : (0.0, 0.0, 0.0)
  18250. */
  18251. get: function () {
  18252. return this._rotation;
  18253. },
  18254. set: function (newRotation) {
  18255. this._rotation = newRotation;
  18256. },
  18257. enumerable: true,
  18258. configurable: true
  18259. });
  18260. Object.defineProperty(TransformNode.prototype, "scaling", {
  18261. /**
  18262. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18263. * Default : (1.0, 1.0, 1.0)
  18264. */
  18265. get: function () {
  18266. return this._scaling;
  18267. },
  18268. /**
  18269. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18270. * Default : (1.0, 1.0, 1.0)
  18271. */
  18272. set: function (newScaling) {
  18273. this._scaling = newScaling;
  18274. },
  18275. enumerable: true,
  18276. configurable: true
  18277. });
  18278. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18279. /**
  18280. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18281. * It's null by default.
  18282. * 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)
  18283. */
  18284. get: function () {
  18285. return this._rotationQuaternion;
  18286. },
  18287. set: function (quaternion) {
  18288. this._rotationQuaternion = quaternion;
  18289. //reset the rotation vector.
  18290. if (quaternion && this.rotation.length()) {
  18291. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18292. }
  18293. },
  18294. enumerable: true,
  18295. configurable: true
  18296. });
  18297. Object.defineProperty(TransformNode.prototype, "forward", {
  18298. /**
  18299. * The forward direction of that transform in world space.
  18300. */
  18301. get: function () {
  18302. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18303. },
  18304. enumerable: true,
  18305. configurable: true
  18306. });
  18307. Object.defineProperty(TransformNode.prototype, "up", {
  18308. /**
  18309. * The up direction of that transform in world space.
  18310. */
  18311. get: function () {
  18312. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18313. },
  18314. enumerable: true,
  18315. configurable: true
  18316. });
  18317. Object.defineProperty(TransformNode.prototype, "right", {
  18318. /**
  18319. * The right direction of that transform in world space.
  18320. */
  18321. get: function () {
  18322. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18323. },
  18324. enumerable: true,
  18325. configurable: true
  18326. });
  18327. /**
  18328. * Returns the latest update of the World matrix
  18329. * Returns a Matrix.
  18330. */
  18331. TransformNode.prototype.getWorldMatrix = function () {
  18332. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18333. this.computeWorldMatrix();
  18334. }
  18335. return this._worldMatrix;
  18336. };
  18337. /** @hidden */
  18338. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18339. return this._worldMatrixDeterminant;
  18340. };
  18341. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18342. /**
  18343. * Returns directly the latest state of the mesh World matrix.
  18344. * A Matrix is returned.
  18345. */
  18346. get: function () {
  18347. return this._worldMatrix;
  18348. },
  18349. enumerable: true,
  18350. configurable: true
  18351. });
  18352. /**
  18353. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18354. * Returns the TransformNode.
  18355. */
  18356. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18357. this._poseMatrix.copyFrom(matrix);
  18358. return this;
  18359. };
  18360. /**
  18361. * Returns the mesh Pose matrix.
  18362. * Returned object : Matrix
  18363. */
  18364. TransformNode.prototype.getPoseMatrix = function () {
  18365. return this._poseMatrix;
  18366. };
  18367. TransformNode.prototype._isSynchronized = function () {
  18368. if (this._isDirty) {
  18369. return false;
  18370. }
  18371. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18372. return false;
  18373. if (this._cache.pivotMatrixUpdated) {
  18374. return false;
  18375. }
  18376. if (this.infiniteDistance) {
  18377. return false;
  18378. }
  18379. if (!this._cache.position.equals(this.position))
  18380. return false;
  18381. if (this.rotationQuaternion) {
  18382. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18383. return false;
  18384. }
  18385. if (!this._cache.rotation.equals(this.rotation))
  18386. return false;
  18387. if (!this._cache.scaling.equals(this.scaling))
  18388. return false;
  18389. return true;
  18390. };
  18391. TransformNode.prototype._initCache = function () {
  18392. _super.prototype._initCache.call(this);
  18393. this._cache.localMatrixUpdated = false;
  18394. this._cache.position = BABYLON.Vector3.Zero();
  18395. this._cache.scaling = BABYLON.Vector3.Zero();
  18396. this._cache.rotation = BABYLON.Vector3.Zero();
  18397. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18398. this._cache.billboardMode = -1;
  18399. };
  18400. TransformNode.prototype.markAsDirty = function (property) {
  18401. if (property === "rotation") {
  18402. this.rotationQuaternion = null;
  18403. }
  18404. this._currentRenderId = Number.MAX_VALUE;
  18405. this._isDirty = true;
  18406. return this;
  18407. };
  18408. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18409. /**
  18410. * Returns the current mesh absolute position.
  18411. * Retuns a Vector3.
  18412. */
  18413. get: function () {
  18414. return this._absolutePosition;
  18415. },
  18416. enumerable: true,
  18417. configurable: true
  18418. });
  18419. /**
  18420. * Sets a new matrix to apply before all other transformation
  18421. * @param matrix defines the transform matrix
  18422. * @returns the current TransformNode
  18423. */
  18424. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18425. return this.setPivotMatrix(matrix, false);
  18426. };
  18427. /**
  18428. * Sets a new pivot matrix to the current node
  18429. * @param matrix defines the new pivot matrix to use
  18430. * @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
  18431. * @returns the current TransformNode
  18432. */
  18433. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18434. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18435. this._pivotMatrix = matrix.clone();
  18436. this._cache.pivotMatrixUpdated = true;
  18437. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18438. if (this._postMultiplyPivotMatrix) {
  18439. if (!this._pivotMatrixInverse) {
  18440. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18441. }
  18442. else {
  18443. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18444. }
  18445. }
  18446. return this;
  18447. };
  18448. /**
  18449. * Returns the mesh pivot matrix.
  18450. * Default : Identity.
  18451. * A Matrix is returned.
  18452. */
  18453. TransformNode.prototype.getPivotMatrix = function () {
  18454. return this._pivotMatrix;
  18455. };
  18456. /**
  18457. * Prevents the World matrix to be computed any longer.
  18458. * Returns the TransformNode.
  18459. */
  18460. TransformNode.prototype.freezeWorldMatrix = function () {
  18461. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18462. this.computeWorldMatrix(true);
  18463. this._isWorldMatrixFrozen = true;
  18464. return this;
  18465. };
  18466. /**
  18467. * Allows back the World matrix computation.
  18468. * Returns the TransformNode.
  18469. */
  18470. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18471. this._isWorldMatrixFrozen = false;
  18472. this.computeWorldMatrix(true);
  18473. return this;
  18474. };
  18475. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18476. /**
  18477. * True if the World matrix has been frozen.
  18478. * Returns a boolean.
  18479. */
  18480. get: function () {
  18481. return this._isWorldMatrixFrozen;
  18482. },
  18483. enumerable: true,
  18484. configurable: true
  18485. });
  18486. /**
  18487. * Retuns the mesh absolute position in the World.
  18488. * Returns a Vector3.
  18489. */
  18490. TransformNode.prototype.getAbsolutePosition = function () {
  18491. this.computeWorldMatrix();
  18492. return this._absolutePosition;
  18493. };
  18494. /**
  18495. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18496. * Returns the TransformNode.
  18497. */
  18498. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18499. if (!absolutePosition) {
  18500. return this;
  18501. }
  18502. var absolutePositionX;
  18503. var absolutePositionY;
  18504. var absolutePositionZ;
  18505. if (absolutePosition.x === undefined) {
  18506. if (arguments.length < 3) {
  18507. return this;
  18508. }
  18509. absolutePositionX = arguments[0];
  18510. absolutePositionY = arguments[1];
  18511. absolutePositionZ = arguments[2];
  18512. }
  18513. else {
  18514. absolutePositionX = absolutePosition.x;
  18515. absolutePositionY = absolutePosition.y;
  18516. absolutePositionZ = absolutePosition.z;
  18517. }
  18518. if (this.parent) {
  18519. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18520. invertParentWorldMatrix.invert();
  18521. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18522. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18523. }
  18524. else {
  18525. this.position.x = absolutePositionX;
  18526. this.position.y = absolutePositionY;
  18527. this.position.z = absolutePositionZ;
  18528. }
  18529. return this;
  18530. };
  18531. /**
  18532. * Sets the mesh position in its local space.
  18533. * Returns the TransformNode.
  18534. */
  18535. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18536. this.computeWorldMatrix();
  18537. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18538. return this;
  18539. };
  18540. /**
  18541. * Returns the mesh position in the local space from the current World matrix values.
  18542. * Returns a new Vector3.
  18543. */
  18544. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18545. this.computeWorldMatrix();
  18546. var invLocalWorldMatrix = this._localWorld.clone();
  18547. invLocalWorldMatrix.invert();
  18548. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18549. };
  18550. /**
  18551. * Translates the mesh along the passed Vector3 in its local space.
  18552. * Returns the TransformNode.
  18553. */
  18554. TransformNode.prototype.locallyTranslate = function (vector3) {
  18555. this.computeWorldMatrix(true);
  18556. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18557. return this;
  18558. };
  18559. /**
  18560. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18561. * @param targetPoint the position (must be in same space as current mesh) to look at
  18562. * @param yawCor optional yaw (y-axis) correction in radians
  18563. * @param pitchCor optional pitch (x-axis) correction in radians
  18564. * @param rollCor optional roll (z-axis) correction in radians
  18565. * @param space the choosen space of the target
  18566. * @returns the TransformNode.
  18567. */
  18568. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18569. if (yawCor === void 0) { yawCor = 0; }
  18570. if (pitchCor === void 0) { pitchCor = 0; }
  18571. if (rollCor === void 0) { rollCor = 0; }
  18572. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18573. var dv = TransformNode._lookAtVectorCache;
  18574. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18575. targetPoint.subtractToRef(pos, dv);
  18576. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18577. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18578. var pitch = Math.atan2(dv.y, len);
  18579. if (this.rotationQuaternion) {
  18580. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18581. }
  18582. else {
  18583. this.rotation.x = pitch + pitchCor;
  18584. this.rotation.y = yaw + yawCor;
  18585. this.rotation.z = rollCor;
  18586. }
  18587. return this;
  18588. };
  18589. /**
  18590. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18591. * This Vector3 is expressed in the World space.
  18592. */
  18593. TransformNode.prototype.getDirection = function (localAxis) {
  18594. var result = BABYLON.Vector3.Zero();
  18595. this.getDirectionToRef(localAxis, result);
  18596. return result;
  18597. };
  18598. /**
  18599. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18600. * localAxis is expressed in the mesh local space.
  18601. * result is computed in the Wordl space from the mesh World matrix.
  18602. * Returns the TransformNode.
  18603. */
  18604. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18605. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18606. return this;
  18607. };
  18608. /**
  18609. * Sets a new pivot point to the current node
  18610. * @param point defines the new pivot point to use
  18611. * @param space defines if the point is in world or local space (local by default)
  18612. * @returns the current TransformNode
  18613. */
  18614. TransformNode.prototype.setPivotPoint = function (point, space) {
  18615. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18616. if (this.getScene().getRenderId() == 0) {
  18617. this.computeWorldMatrix(true);
  18618. }
  18619. var wm = this.getWorldMatrix();
  18620. if (space == BABYLON.Space.WORLD) {
  18621. var tmat = BABYLON.Tmp.Matrix[0];
  18622. wm.invertToRef(tmat);
  18623. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18624. }
  18625. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18626. };
  18627. /**
  18628. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18629. */
  18630. TransformNode.prototype.getPivotPoint = function () {
  18631. var point = BABYLON.Vector3.Zero();
  18632. this.getPivotPointToRef(point);
  18633. return point;
  18634. };
  18635. /**
  18636. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18637. * Returns the TransformNode.
  18638. */
  18639. TransformNode.prototype.getPivotPointToRef = function (result) {
  18640. result.x = -this._pivotMatrix.m[12];
  18641. result.y = -this._pivotMatrix.m[13];
  18642. result.z = -this._pivotMatrix.m[14];
  18643. return this;
  18644. };
  18645. /**
  18646. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18647. */
  18648. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18649. var point = BABYLON.Vector3.Zero();
  18650. this.getAbsolutePivotPointToRef(point);
  18651. return point;
  18652. };
  18653. /**
  18654. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18655. * Returns the TransformNode.
  18656. */
  18657. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18658. result.x = this._pivotMatrix.m[12];
  18659. result.y = this._pivotMatrix.m[13];
  18660. result.z = this._pivotMatrix.m[14];
  18661. this.getPivotPointToRef(result);
  18662. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18663. return this;
  18664. };
  18665. /**
  18666. * Defines the passed node as the parent of the current node.
  18667. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18668. * Returns the TransformNode.
  18669. */
  18670. TransformNode.prototype.setParent = function (node) {
  18671. if (!node && !this.parent) {
  18672. return this;
  18673. }
  18674. if (!node) {
  18675. var rotation = BABYLON.Tmp.Quaternion[0];
  18676. var position = BABYLON.Tmp.Vector3[0];
  18677. var scale = BABYLON.Tmp.Vector3[1];
  18678. if (this.parent && this.parent.computeWorldMatrix) {
  18679. this.parent.computeWorldMatrix(true);
  18680. }
  18681. this.computeWorldMatrix(true);
  18682. this.getWorldMatrix().decompose(scale, rotation, position);
  18683. if (this.rotationQuaternion) {
  18684. this.rotationQuaternion.copyFrom(rotation);
  18685. }
  18686. else {
  18687. rotation.toEulerAnglesToRef(this.rotation);
  18688. }
  18689. this.scaling.x = scale.x;
  18690. this.scaling.y = scale.y;
  18691. this.scaling.z = scale.z;
  18692. this.position.x = position.x;
  18693. this.position.y = position.y;
  18694. this.position.z = position.z;
  18695. }
  18696. else {
  18697. var rotation = BABYLON.Tmp.Quaternion[0];
  18698. var position = BABYLON.Tmp.Vector3[0];
  18699. var scale = BABYLON.Tmp.Vector3[1];
  18700. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18701. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18702. this.computeWorldMatrix(true);
  18703. node.computeWorldMatrix(true);
  18704. node.getWorldMatrix().invertToRef(invParentMatrix);
  18705. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18706. diffMatrix.decompose(scale, rotation, position);
  18707. if (this.rotationQuaternion) {
  18708. this.rotationQuaternion.copyFrom(rotation);
  18709. }
  18710. else {
  18711. rotation.toEulerAnglesToRef(this.rotation);
  18712. }
  18713. this.position.x = position.x;
  18714. this.position.y = position.y;
  18715. this.position.z = position.z;
  18716. this.scaling.x = scale.x;
  18717. this.scaling.y = scale.y;
  18718. this.scaling.z = scale.z;
  18719. }
  18720. this.parent = node;
  18721. return this;
  18722. };
  18723. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18724. get: function () {
  18725. return this._nonUniformScaling;
  18726. },
  18727. enumerable: true,
  18728. configurable: true
  18729. });
  18730. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18731. if (this._nonUniformScaling === value) {
  18732. return false;
  18733. }
  18734. this._nonUniformScaling = value;
  18735. return true;
  18736. };
  18737. /**
  18738. * Attach the current TransformNode to another TransformNode associated with a bone
  18739. * @param bone Bone affecting the TransformNode
  18740. * @param affectedTransformNode TransformNode associated with the bone
  18741. */
  18742. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18743. this._transformToBoneReferal = affectedTransformNode;
  18744. this.parent = bone;
  18745. if (bone.getWorldMatrix().determinant() < 0) {
  18746. this.scalingDeterminant *= -1;
  18747. }
  18748. return this;
  18749. };
  18750. TransformNode.prototype.detachFromBone = function () {
  18751. if (!this.parent) {
  18752. return this;
  18753. }
  18754. if (this.parent.getWorldMatrix().determinant() < 0) {
  18755. this.scalingDeterminant *= -1;
  18756. }
  18757. this._transformToBoneReferal = null;
  18758. this.parent = null;
  18759. return this;
  18760. };
  18761. /**
  18762. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18763. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18764. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18765. * The passed axis is also normalized.
  18766. * Returns the TransformNode.
  18767. */
  18768. TransformNode.prototype.rotate = function (axis, amount, space) {
  18769. axis.normalize();
  18770. if (!this.rotationQuaternion) {
  18771. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18772. this.rotation = BABYLON.Vector3.Zero();
  18773. }
  18774. var rotationQuaternion;
  18775. if (!space || space === BABYLON.Space.LOCAL) {
  18776. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18777. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18778. }
  18779. else {
  18780. if (this.parent) {
  18781. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18782. invertParentWorldMatrix.invert();
  18783. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18784. }
  18785. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18786. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18787. }
  18788. return this;
  18789. };
  18790. /**
  18791. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18792. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18793. * The passed axis is also normalized.
  18794. * Returns the TransformNode.
  18795. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18796. */
  18797. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18798. axis.normalize();
  18799. if (!this.rotationQuaternion) {
  18800. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18801. this.rotation.copyFromFloats(0, 0, 0);
  18802. }
  18803. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18804. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18805. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18806. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18807. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18808. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18809. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18810. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18811. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18812. return this;
  18813. };
  18814. /**
  18815. * Translates the mesh along the axis vector for the passed distance in the given space.
  18816. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18817. * Returns the TransformNode.
  18818. */
  18819. TransformNode.prototype.translate = function (axis, distance, space) {
  18820. var displacementVector = axis.scale(distance);
  18821. if (!space || space === BABYLON.Space.LOCAL) {
  18822. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18823. this.setPositionWithLocalVector(tempV3);
  18824. }
  18825. else {
  18826. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18827. }
  18828. return this;
  18829. };
  18830. /**
  18831. * Adds a rotation step to the mesh current rotation.
  18832. * x, y, z are Euler angles expressed in radians.
  18833. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18834. * This means this rotation is made in the mesh local space only.
  18835. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18836. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18837. * ```javascript
  18838. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18839. * ```
  18840. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18841. * 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.
  18842. * Returns the TransformNode.
  18843. */
  18844. TransformNode.prototype.addRotation = function (x, y, z) {
  18845. var rotationQuaternion;
  18846. if (this.rotationQuaternion) {
  18847. rotationQuaternion = this.rotationQuaternion;
  18848. }
  18849. else {
  18850. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18851. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18852. }
  18853. var accumulation = BABYLON.Tmp.Quaternion[0];
  18854. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18855. rotationQuaternion.multiplyInPlace(accumulation);
  18856. if (!this.rotationQuaternion) {
  18857. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18858. }
  18859. return this;
  18860. };
  18861. /**
  18862. * Computes the mesh World matrix and returns it.
  18863. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18864. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18865. * If the parameter `force`is set to `true`, the actual computation is done.
  18866. * Returns the mesh World Matrix.
  18867. */
  18868. TransformNode.prototype.computeWorldMatrix = function (force) {
  18869. if (this._isWorldMatrixFrozen) {
  18870. return this._worldMatrix;
  18871. }
  18872. if (!force && this.isSynchronized(true)) {
  18873. this._currentRenderId = this.getScene().getRenderId();
  18874. return this._worldMatrix;
  18875. }
  18876. this._cache.position.copyFrom(this.position);
  18877. this._cache.scaling.copyFrom(this.scaling);
  18878. this._cache.pivotMatrixUpdated = false;
  18879. this._cache.billboardMode = this.billboardMode;
  18880. this._currentRenderId = this.getScene().getRenderId();
  18881. this._childRenderId = this.getScene().getRenderId();
  18882. this._isDirty = false;
  18883. // Scaling
  18884. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18885. // Rotation
  18886. //rotate, if quaternion is set and rotation was used
  18887. if (this.rotationQuaternion) {
  18888. var len = this.rotation.length();
  18889. if (len) {
  18890. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18891. this.rotation.copyFromFloats(0, 0, 0);
  18892. }
  18893. }
  18894. if (this.rotationQuaternion) {
  18895. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18896. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18897. }
  18898. else {
  18899. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18900. this._cache.rotation.copyFrom(this.rotation);
  18901. }
  18902. // Translation
  18903. var camera = this.getScene().activeCamera;
  18904. if (this.infiniteDistance && !this.parent && camera) {
  18905. var cameraWorldMatrix = camera.getWorldMatrix();
  18906. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18907. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18908. }
  18909. else {
  18910. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18911. }
  18912. // Composing transformations
  18913. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18914. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18915. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18916. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18917. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18918. // Need to decompose each rotation here
  18919. var currentPosition = BABYLON.Tmp.Vector3[3];
  18920. if (this.parent && this.parent.getWorldMatrix) {
  18921. if (this._transformToBoneReferal) {
  18922. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18923. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18924. }
  18925. else {
  18926. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18927. }
  18928. }
  18929. else {
  18930. currentPosition.copyFrom(this.position);
  18931. }
  18932. currentPosition.subtractInPlace(camera.globalPosition);
  18933. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18934. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18935. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18936. }
  18937. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18938. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18939. }
  18940. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18941. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18942. }
  18943. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18944. }
  18945. else {
  18946. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18947. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18948. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18949. }
  18950. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18951. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18952. }
  18953. // Post multiply inverse of pivotMatrix
  18954. if (this._postMultiplyPivotMatrix) {
  18955. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  18956. }
  18957. // Local world
  18958. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18959. // Parent
  18960. if (this.parent && this.parent.getWorldMatrix) {
  18961. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18962. if (this._transformToBoneReferal) {
  18963. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18964. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18965. }
  18966. else {
  18967. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18968. }
  18969. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18970. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18971. this._worldMatrix.copyFrom(this._localWorld);
  18972. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18973. }
  18974. else {
  18975. if (this._transformToBoneReferal) {
  18976. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18977. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18978. }
  18979. else {
  18980. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18981. }
  18982. }
  18983. this._markSyncedWithParent();
  18984. }
  18985. else {
  18986. this._worldMatrix.copyFrom(this._localWorld);
  18987. }
  18988. // Normal matrix
  18989. if (!this.ignoreNonUniformScaling) {
  18990. if (this.scaling.isNonUniform) {
  18991. this._updateNonUniformScalingState(true);
  18992. }
  18993. else if (this.parent && this.parent._nonUniformScaling) {
  18994. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18995. }
  18996. else {
  18997. this._updateNonUniformScalingState(false);
  18998. }
  18999. }
  19000. else {
  19001. this._updateNonUniformScalingState(false);
  19002. }
  19003. this._afterComputeWorldMatrix();
  19004. // Absolute position
  19005. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19006. // Callbacks
  19007. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19008. if (!this._poseMatrix) {
  19009. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19010. }
  19011. // Cache the determinant
  19012. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19013. return this._worldMatrix;
  19014. };
  19015. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19016. };
  19017. /**
  19018. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19019. * @param func: callback function to add
  19020. *
  19021. * Returns the TransformNode.
  19022. */
  19023. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19024. this.onAfterWorldMatrixUpdateObservable.add(func);
  19025. return this;
  19026. };
  19027. /**
  19028. * Removes a registered callback function.
  19029. * Returns the TransformNode.
  19030. */
  19031. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19032. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19033. return this;
  19034. };
  19035. /**
  19036. * Clone the current transform node
  19037. * Returns the new transform node
  19038. * @param name Name of the new clone
  19039. * @param newParent New parent for the clone
  19040. * @param doNotCloneChildren Do not clone children hierarchy
  19041. */
  19042. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19043. var _this = this;
  19044. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19045. result.name = name;
  19046. result.id = name;
  19047. if (newParent) {
  19048. result.parent = newParent;
  19049. }
  19050. if (!doNotCloneChildren) {
  19051. // Children
  19052. var directDescendants = this.getDescendants(true);
  19053. for (var index = 0; index < directDescendants.length; index++) {
  19054. var child = directDescendants[index];
  19055. if (child.clone) {
  19056. child.clone(name + "." + child.name, result);
  19057. }
  19058. }
  19059. }
  19060. return result;
  19061. };
  19062. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19063. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19064. serializationObject.type = this.getClassName();
  19065. // Parent
  19066. if (this.parent) {
  19067. serializationObject.parentId = this.parent.id;
  19068. }
  19069. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19070. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19071. }
  19072. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19073. serializationObject.isEnabled = this.isEnabled();
  19074. // Parent
  19075. if (this.parent) {
  19076. serializationObject.parentId = this.parent.id;
  19077. }
  19078. return serializationObject;
  19079. };
  19080. // Statics
  19081. /**
  19082. * Returns a new TransformNode object parsed from the source provided.
  19083. * The parameter `parsedMesh` is the source.
  19084. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19085. */
  19086. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19087. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19088. if (BABYLON.Tags) {
  19089. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19090. }
  19091. if (parsedTransformNode.localMatrix) {
  19092. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19093. }
  19094. else if (parsedTransformNode.pivotMatrix) {
  19095. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19096. }
  19097. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19098. // Parent
  19099. if (parsedTransformNode.parentId) {
  19100. transformNode._waitingParentId = parsedTransformNode.parentId;
  19101. }
  19102. return transformNode;
  19103. };
  19104. /**
  19105. * Releases resources associated with this transform node.
  19106. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19107. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19108. */
  19109. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19110. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19111. // Animations
  19112. this.getScene().stopAnimation(this);
  19113. // Remove from scene
  19114. this.getScene().removeTransformNode(this);
  19115. this.onAfterWorldMatrixUpdateObservable.clear();
  19116. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19117. };
  19118. // Statics
  19119. TransformNode.BILLBOARDMODE_NONE = 0;
  19120. TransformNode.BILLBOARDMODE_X = 1;
  19121. TransformNode.BILLBOARDMODE_Y = 2;
  19122. TransformNode.BILLBOARDMODE_Z = 4;
  19123. TransformNode.BILLBOARDMODE_ALL = 7;
  19124. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19125. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19126. __decorate([
  19127. BABYLON.serializeAsVector3()
  19128. ], TransformNode.prototype, "_rotation", void 0);
  19129. __decorate([
  19130. BABYLON.serializeAsQuaternion()
  19131. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19132. __decorate([
  19133. BABYLON.serializeAsVector3()
  19134. ], TransformNode.prototype, "_scaling", void 0);
  19135. __decorate([
  19136. BABYLON.serialize()
  19137. ], TransformNode.prototype, "billboardMode", void 0);
  19138. __decorate([
  19139. BABYLON.serialize()
  19140. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19141. __decorate([
  19142. BABYLON.serialize()
  19143. ], TransformNode.prototype, "infiniteDistance", void 0);
  19144. __decorate([
  19145. BABYLON.serialize()
  19146. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19147. __decorate([
  19148. BABYLON.serializeAsVector3()
  19149. ], TransformNode.prototype, "position", void 0);
  19150. return TransformNode;
  19151. }(BABYLON.Node));
  19152. BABYLON.TransformNode = TransformNode;
  19153. })(BABYLON || (BABYLON = {}));
  19154. //# sourceMappingURL=babylon.transformNode.js.map
  19155. var BABYLON;
  19156. (function (BABYLON) {
  19157. /**
  19158. * Class used to store all common mesh properties
  19159. */
  19160. var AbstractMesh = /** @class */ (function (_super) {
  19161. __extends(AbstractMesh, _super);
  19162. // Constructor
  19163. /**
  19164. * Creates a new AbstractMesh
  19165. * @param name defines the name of the mesh
  19166. * @param scene defines the hosting scene
  19167. */
  19168. function AbstractMesh(name, scene) {
  19169. if (scene === void 0) { scene = null; }
  19170. var _this = _super.call(this, name, scene, false) || this;
  19171. _this._facetNb = 0; // facet number
  19172. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19173. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19174. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19175. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19176. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19177. _this._subDiv = {
  19178. max: 1,
  19179. X: 1,
  19180. Y: 1,
  19181. Z: 1
  19182. };
  19183. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19184. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19185. // Events
  19186. /**
  19187. * An event triggered when this mesh collides with another one
  19188. */
  19189. _this.onCollideObservable = new BABYLON.Observable();
  19190. /**
  19191. * An event triggered when the collision's position changes
  19192. */
  19193. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19194. /**
  19195. * An event triggered when material is changed
  19196. */
  19197. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19198. // Properties
  19199. /**
  19200. * Gets or sets the orientation for POV movement & rotation
  19201. */
  19202. _this.definedFacingForward = true;
  19203. /**
  19204. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19205. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19206. * * 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.
  19207. * @see http://doc.babylonjs.com/features/occlusionquery
  19208. */
  19209. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19210. /**
  19211. * 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:
  19212. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19213. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19214. * * 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.
  19215. * @see http://doc.babylonjs.com/features/occlusionquery
  19216. */
  19217. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19218. /**
  19219. * 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.
  19220. * The default value is -1 which means don't break the query and wait till the result
  19221. * @see http://doc.babylonjs.com/features/occlusionquery
  19222. */
  19223. _this.occlusionRetryCount = -1;
  19224. /** @hidden */
  19225. _this._occlusionInternalRetryCounter = 0;
  19226. /** @hidden */
  19227. _this._isOccluded = false;
  19228. /** @hidden */
  19229. _this._isOcclusionQueryInProgress = false;
  19230. _this._visibility = 1.0;
  19231. /** Gets or sets the alpha index used to sort transparent meshes
  19232. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19233. */
  19234. _this.alphaIndex = Number.MAX_VALUE;
  19235. /**
  19236. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19237. */
  19238. _this.isVisible = true;
  19239. /**
  19240. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19241. */
  19242. _this.isPickable = true;
  19243. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19244. _this.showSubMeshesBoundingBox = false;
  19245. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19246. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19247. */
  19248. _this.isBlocker = false;
  19249. /**
  19250. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19251. */
  19252. _this.enablePointerMoveEvents = false;
  19253. /**
  19254. * Specifies the rendering group id for this mesh (0 by default)
  19255. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19256. */
  19257. _this.renderingGroupId = 0;
  19258. _this._receiveShadows = false;
  19259. /**
  19260. * Gets or sets a boolean indicating if the outline must be rendered as well
  19261. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19262. */
  19263. _this.renderOutline = false;
  19264. /** Defines color to use when rendering outline */
  19265. _this.outlineColor = BABYLON.Color3.Red();
  19266. /** Define width to use when rendering outline */
  19267. _this.outlineWidth = 0.02;
  19268. /**
  19269. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19270. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19271. */
  19272. _this.renderOverlay = false;
  19273. /** Defines color to use when rendering overlay */
  19274. _this.overlayColor = BABYLON.Color3.Red();
  19275. /** Defines alpha to use when rendering overlay */
  19276. _this.overlayAlpha = 0.5;
  19277. _this._hasVertexAlpha = false;
  19278. _this._useVertexColors = true;
  19279. _this._computeBonesUsingShaders = true;
  19280. _this._numBoneInfluencers = 4;
  19281. _this._applyFog = true;
  19282. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19283. _this.useOctreeForRenderingSelection = true;
  19284. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19285. _this.useOctreeForPicking = true;
  19286. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19287. _this.useOctreeForCollisions = true;
  19288. _this._layerMask = 0x0FFFFFFF;
  19289. /**
  19290. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19291. */
  19292. _this.alwaysSelectAsActiveMesh = false;
  19293. /**
  19294. * Gets or sets the current action manager
  19295. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19296. */
  19297. _this.actionManager = null;
  19298. /**
  19299. * Gets or sets impostor used for physic simulation
  19300. * @see http://doc.babylonjs.com/features/physics_engine
  19301. */
  19302. _this.physicsImpostor = null;
  19303. // Collisions
  19304. _this._checkCollisions = false;
  19305. _this._collisionMask = -1;
  19306. _this._collisionGroup = -1;
  19307. /**
  19308. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19309. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19310. */
  19311. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19312. /**
  19313. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19314. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19315. */
  19316. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19317. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19318. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19319. // Edges
  19320. /**
  19321. * Defines edge width used when edgesRenderer is enabled
  19322. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19323. */
  19324. _this.edgesWidth = 1;
  19325. /**
  19326. * Defines edge color used when edgesRenderer is enabled
  19327. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19328. */
  19329. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19330. // Cache
  19331. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19332. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19333. /** @hidden */
  19334. _this._renderId = 0;
  19335. /** @hidden */
  19336. _this._intersectionsInProgress = new Array();
  19337. /** @hidden */
  19338. _this._unIndexed = false;
  19339. /** @hidden */
  19340. _this._lightSources = new Array();
  19341. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19342. if (collidedMesh === void 0) { collidedMesh = null; }
  19343. //TODO move this to the collision coordinator!
  19344. if (_this.getScene().workerCollisions)
  19345. newPosition.multiplyInPlace(_this._collider._radius);
  19346. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19347. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19348. _this.position.addInPlace(_this._diffPositionForCollisions);
  19349. }
  19350. if (collidedMesh) {
  19351. _this.onCollideObservable.notifyObservers(collidedMesh);
  19352. }
  19353. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19354. };
  19355. _this.getScene().addMesh(_this);
  19356. _this._resyncLightSources();
  19357. return _this;
  19358. }
  19359. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19360. /**
  19361. * No billboard
  19362. */
  19363. get: function () {
  19364. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19365. },
  19366. enumerable: true,
  19367. configurable: true
  19368. });
  19369. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19370. /** Billboard on X axis */
  19371. get: function () {
  19372. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19373. },
  19374. enumerable: true,
  19375. configurable: true
  19376. });
  19377. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19378. /** Billboard on Y axis */
  19379. get: function () {
  19380. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19381. },
  19382. enumerable: true,
  19383. configurable: true
  19384. });
  19385. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19386. /** Billboard on Z axis */
  19387. get: function () {
  19388. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19389. },
  19390. enumerable: true,
  19391. configurable: true
  19392. });
  19393. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19394. /** Billboard on all axes */
  19395. get: function () {
  19396. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19397. },
  19398. enumerable: true,
  19399. configurable: true
  19400. });
  19401. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19402. /**
  19403. * Gets the number of facets in the mesh
  19404. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19405. */
  19406. get: function () {
  19407. return this._facetNb;
  19408. },
  19409. enumerable: true,
  19410. configurable: true
  19411. });
  19412. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19413. /**
  19414. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19415. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19416. */
  19417. get: function () {
  19418. return this._partitioningSubdivisions;
  19419. },
  19420. set: function (nb) {
  19421. this._partitioningSubdivisions = nb;
  19422. },
  19423. enumerable: true,
  19424. configurable: true
  19425. });
  19426. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19427. /**
  19428. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19429. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19430. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19431. */
  19432. get: function () {
  19433. return this._partitioningBBoxRatio;
  19434. },
  19435. set: function (ratio) {
  19436. this._partitioningBBoxRatio = ratio;
  19437. },
  19438. enumerable: true,
  19439. configurable: true
  19440. });
  19441. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19442. /**
  19443. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19444. * Works only for updatable meshes.
  19445. * Doesn't work with multi-materials
  19446. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19447. */
  19448. get: function () {
  19449. return this._facetDepthSort;
  19450. },
  19451. set: function (sort) {
  19452. this._facetDepthSort = sort;
  19453. },
  19454. enumerable: true,
  19455. configurable: true
  19456. });
  19457. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19458. /**
  19459. * The location (Vector3) where the facet depth sort must be computed from.
  19460. * By default, the active camera position.
  19461. * Used only when facet depth sort is enabled
  19462. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19463. */
  19464. get: function () {
  19465. return this._facetDepthSortFrom;
  19466. },
  19467. set: function (location) {
  19468. this._facetDepthSortFrom = location;
  19469. },
  19470. enumerable: true,
  19471. configurable: true
  19472. });
  19473. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19474. /**
  19475. * gets a boolean indicating if facetData is enabled
  19476. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19477. */
  19478. get: function () {
  19479. return this._facetDataEnabled;
  19480. },
  19481. enumerable: true,
  19482. configurable: true
  19483. });
  19484. /** @hidden */
  19485. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19486. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19487. return false;
  19488. }
  19489. this._markSubMeshesAsMiscDirty();
  19490. return true;
  19491. };
  19492. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19493. /** Set a function to call when this mesh collides with another one */
  19494. set: function (callback) {
  19495. if (this._onCollideObserver) {
  19496. this.onCollideObservable.remove(this._onCollideObserver);
  19497. }
  19498. this._onCollideObserver = this.onCollideObservable.add(callback);
  19499. },
  19500. enumerable: true,
  19501. configurable: true
  19502. });
  19503. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19504. /** Set a function to call when the collision's position changes */
  19505. set: function (callback) {
  19506. if (this._onCollisionPositionChangeObserver) {
  19507. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19508. }
  19509. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19510. },
  19511. enumerable: true,
  19512. configurable: true
  19513. });
  19514. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19515. /**
  19516. * 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
  19517. * @see http://doc.babylonjs.com/features/occlusionquery
  19518. */
  19519. get: function () {
  19520. return this._isOccluded;
  19521. },
  19522. set: function (value) {
  19523. this._isOccluded = value;
  19524. },
  19525. enumerable: true,
  19526. configurable: true
  19527. });
  19528. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19529. /**
  19530. * Flag to check the progress status of the query
  19531. * @see http://doc.babylonjs.com/features/occlusionquery
  19532. */
  19533. get: function () {
  19534. return this._isOcclusionQueryInProgress;
  19535. },
  19536. enumerable: true,
  19537. configurable: true
  19538. });
  19539. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19540. /**
  19541. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19542. */
  19543. get: function () {
  19544. return this._visibility;
  19545. },
  19546. /**
  19547. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19548. */
  19549. set: function (value) {
  19550. if (this._visibility === value) {
  19551. return;
  19552. }
  19553. this._visibility = value;
  19554. this._markSubMeshesAsMiscDirty();
  19555. },
  19556. enumerable: true,
  19557. configurable: true
  19558. });
  19559. Object.defineProperty(AbstractMesh.prototype, "material", {
  19560. /** Gets or sets current material */
  19561. get: function () {
  19562. return this._material;
  19563. },
  19564. set: function (value) {
  19565. if (this._material === value) {
  19566. return;
  19567. }
  19568. this._material = value;
  19569. if (this.onMaterialChangedObservable.hasObservers) {
  19570. this.onMaterialChangedObservable.notifyObservers(this);
  19571. }
  19572. if (!this.subMeshes) {
  19573. return;
  19574. }
  19575. this._unBindEffect();
  19576. },
  19577. enumerable: true,
  19578. configurable: true
  19579. });
  19580. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19581. /**
  19582. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19583. * @see http://doc.babylonjs.com/babylon101/shadows
  19584. */
  19585. get: function () {
  19586. return this._receiveShadows;
  19587. },
  19588. set: function (value) {
  19589. if (this._receiveShadows === value) {
  19590. return;
  19591. }
  19592. this._receiveShadows = value;
  19593. this._markSubMeshesAsLightDirty();
  19594. },
  19595. enumerable: true,
  19596. configurable: true
  19597. });
  19598. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19599. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19600. get: function () {
  19601. return this._hasVertexAlpha;
  19602. },
  19603. set: function (value) {
  19604. if (this._hasVertexAlpha === value) {
  19605. return;
  19606. }
  19607. this._hasVertexAlpha = value;
  19608. this._markSubMeshesAsAttributesDirty();
  19609. this._markSubMeshesAsMiscDirty();
  19610. },
  19611. enumerable: true,
  19612. configurable: true
  19613. });
  19614. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19615. /** 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) */
  19616. get: function () {
  19617. return this._useVertexColors;
  19618. },
  19619. set: function (value) {
  19620. if (this._useVertexColors === value) {
  19621. return;
  19622. }
  19623. this._useVertexColors = value;
  19624. this._markSubMeshesAsAttributesDirty();
  19625. },
  19626. enumerable: true,
  19627. configurable: true
  19628. });
  19629. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19630. /**
  19631. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19632. */
  19633. get: function () {
  19634. return this._computeBonesUsingShaders;
  19635. },
  19636. set: function (value) {
  19637. if (this._computeBonesUsingShaders === value) {
  19638. return;
  19639. }
  19640. this._computeBonesUsingShaders = value;
  19641. this._markSubMeshesAsAttributesDirty();
  19642. },
  19643. enumerable: true,
  19644. configurable: true
  19645. });
  19646. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19647. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19648. get: function () {
  19649. return this._numBoneInfluencers;
  19650. },
  19651. set: function (value) {
  19652. if (this._numBoneInfluencers === value) {
  19653. return;
  19654. }
  19655. this._numBoneInfluencers = value;
  19656. this._markSubMeshesAsAttributesDirty();
  19657. },
  19658. enumerable: true,
  19659. configurable: true
  19660. });
  19661. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19662. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19663. get: function () {
  19664. return this._applyFog;
  19665. },
  19666. set: function (value) {
  19667. if (this._applyFog === value) {
  19668. return;
  19669. }
  19670. this._applyFog = value;
  19671. this._markSubMeshesAsMiscDirty();
  19672. },
  19673. enumerable: true,
  19674. configurable: true
  19675. });
  19676. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19677. /**
  19678. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19679. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19680. */
  19681. get: function () {
  19682. return this._layerMask;
  19683. },
  19684. set: function (value) {
  19685. if (value === this._layerMask) {
  19686. return;
  19687. }
  19688. this._layerMask = value;
  19689. this._resyncLightSources();
  19690. },
  19691. enumerable: true,
  19692. configurable: true
  19693. });
  19694. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19695. /**
  19696. * Gets or sets a collision mask used to mask collisions (default is -1).
  19697. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19698. */
  19699. get: function () {
  19700. return this._collisionMask;
  19701. },
  19702. set: function (mask) {
  19703. this._collisionMask = !isNaN(mask) ? mask : -1;
  19704. },
  19705. enumerable: true,
  19706. configurable: true
  19707. });
  19708. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19709. /**
  19710. * Gets or sets the current collision group mask (-1 by default).
  19711. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19712. */
  19713. get: function () {
  19714. return this._collisionGroup;
  19715. },
  19716. set: function (mask) {
  19717. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19718. },
  19719. enumerable: true,
  19720. configurable: true
  19721. });
  19722. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19723. /** @hidden */
  19724. get: function () {
  19725. return null;
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19731. get: function () {
  19732. return this._skeleton;
  19733. },
  19734. /**
  19735. * Gets or sets a skeleton to apply skining transformations
  19736. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19737. */
  19738. set: function (value) {
  19739. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19740. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19741. }
  19742. if (value && value.needInitialSkinMatrix) {
  19743. value._registerMeshWithPoseMatrix(this);
  19744. }
  19745. this._skeleton = value;
  19746. if (!this._skeleton) {
  19747. this._bonesTransformMatrices = null;
  19748. }
  19749. this._markSubMeshesAsAttributesDirty();
  19750. },
  19751. enumerable: true,
  19752. configurable: true
  19753. });
  19754. /**
  19755. * Returns the string "AbstractMesh"
  19756. * @returns "AbstractMesh"
  19757. */
  19758. AbstractMesh.prototype.getClassName = function () {
  19759. return "AbstractMesh";
  19760. };
  19761. /**
  19762. * Gets a string representation of the current mesh
  19763. * @param fullDetails defines a boolean indicating if full details must be included
  19764. * @returns a string representation of the current mesh
  19765. */
  19766. AbstractMesh.prototype.toString = function (fullDetails) {
  19767. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19768. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19769. if (this._skeleton) {
  19770. ret += ", skeleton: " + this._skeleton.name;
  19771. }
  19772. if (fullDetails) {
  19773. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19774. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19775. }
  19776. return ret;
  19777. };
  19778. /** @hidden */
  19779. AbstractMesh.prototype._rebuild = function () {
  19780. if (this._occlusionQuery) {
  19781. this._occlusionQuery = null;
  19782. }
  19783. if (this._edgesRenderer) {
  19784. this._edgesRenderer._rebuild();
  19785. }
  19786. if (!this.subMeshes) {
  19787. return;
  19788. }
  19789. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19790. var subMesh = _a[_i];
  19791. subMesh._rebuild();
  19792. }
  19793. };
  19794. /** @hidden */
  19795. AbstractMesh.prototype._resyncLightSources = function () {
  19796. this._lightSources.length = 0;
  19797. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19798. var light = _a[_i];
  19799. if (!light.isEnabled()) {
  19800. continue;
  19801. }
  19802. if (light.canAffectMesh(this)) {
  19803. this._lightSources.push(light);
  19804. }
  19805. }
  19806. this._markSubMeshesAsLightDirty();
  19807. };
  19808. /** @hidden */
  19809. AbstractMesh.prototype._resyncLighSource = function (light) {
  19810. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19811. var index = this._lightSources.indexOf(light);
  19812. if (index === -1) {
  19813. if (!isIn) {
  19814. return;
  19815. }
  19816. this._lightSources.push(light);
  19817. }
  19818. else {
  19819. if (isIn) {
  19820. return;
  19821. }
  19822. this._lightSources.splice(index, 1);
  19823. }
  19824. this._markSubMeshesAsLightDirty();
  19825. };
  19826. /** @hidden */
  19827. AbstractMesh.prototype._unBindEffect = function () {
  19828. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19829. var subMesh = _a[_i];
  19830. subMesh.setEffect(null);
  19831. }
  19832. };
  19833. /** @hidden */
  19834. AbstractMesh.prototype._removeLightSource = function (light) {
  19835. var index = this._lightSources.indexOf(light);
  19836. if (index === -1) {
  19837. return;
  19838. }
  19839. this._lightSources.splice(index, 1);
  19840. this._markSubMeshesAsLightDirty();
  19841. };
  19842. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19843. if (!this.subMeshes) {
  19844. return;
  19845. }
  19846. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19847. var subMesh = _a[_i];
  19848. if (subMesh._materialDefines) {
  19849. func(subMesh._materialDefines);
  19850. }
  19851. }
  19852. };
  19853. /** @hidden */
  19854. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19855. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19856. };
  19857. /** @hidden */
  19858. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19859. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19860. };
  19861. /** @hidden */
  19862. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19863. if (!this.subMeshes) {
  19864. return;
  19865. }
  19866. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19867. var subMesh = _a[_i];
  19868. var material = subMesh.getMaterial();
  19869. if (material) {
  19870. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19871. }
  19872. }
  19873. };
  19874. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19875. /**
  19876. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19877. */
  19878. get: function () {
  19879. return this._scaling;
  19880. },
  19881. set: function (newScaling) {
  19882. this._scaling = newScaling;
  19883. if (this.physicsImpostor) {
  19884. this.physicsImpostor.forceUpdate();
  19885. }
  19886. },
  19887. enumerable: true,
  19888. configurable: true
  19889. });
  19890. // Methods
  19891. /**
  19892. * Disables the mesh edge rendering mode
  19893. * @returns the currentAbstractMesh
  19894. */
  19895. AbstractMesh.prototype.disableEdgesRendering = function () {
  19896. if (this._edgesRenderer) {
  19897. this._edgesRenderer.dispose();
  19898. this._edgesRenderer = null;
  19899. }
  19900. return this;
  19901. };
  19902. /**
  19903. * Enables the edge rendering mode on the mesh.
  19904. * This mode makes the mesh edges visible
  19905. * @param epsilon defines the maximal distance between two angles to detect a face
  19906. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19907. * @returns the currentAbstractMesh
  19908. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19909. */
  19910. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19911. if (epsilon === void 0) { epsilon = 0.95; }
  19912. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19913. this.disableEdgesRendering();
  19914. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19915. return this;
  19916. };
  19917. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  19918. /**
  19919. * Gets the edgesRenderer associated with the mesh
  19920. */
  19921. get: function () {
  19922. return this._edgesRenderer;
  19923. },
  19924. enumerable: true,
  19925. configurable: true
  19926. });
  19927. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19928. /**
  19929. * Returns true if the mesh is blocked. Implemented by child classes
  19930. */
  19931. get: function () {
  19932. return false;
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. /**
  19938. * Returns the mesh itself by default. Implemented by child classes
  19939. * @param camera defines the camera to use to pick the right LOD level
  19940. * @returns the currentAbstractMesh
  19941. */
  19942. AbstractMesh.prototype.getLOD = function (camera) {
  19943. return this;
  19944. };
  19945. /**
  19946. * Returns 0 by default. Implemented by child classes
  19947. * @returns an integer
  19948. */
  19949. AbstractMesh.prototype.getTotalVertices = function () {
  19950. return 0;
  19951. };
  19952. /**
  19953. * Returns null by default. Implemented by child classes
  19954. * @returns null
  19955. */
  19956. AbstractMesh.prototype.getIndices = function () {
  19957. return null;
  19958. };
  19959. /**
  19960. * Returns the array of the requested vertex data kind. Implemented by child classes
  19961. * @param kind defines the vertex data kind to use
  19962. * @returns null
  19963. */
  19964. AbstractMesh.prototype.getVerticesData = function (kind) {
  19965. return null;
  19966. };
  19967. /**
  19968. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19969. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19970. * Note that a new underlying VertexBuffer object is created each call.
  19971. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19972. * @param kind defines vertex data kind:
  19973. * * BABYLON.VertexBuffer.PositionKind
  19974. * * BABYLON.VertexBuffer.UVKind
  19975. * * BABYLON.VertexBuffer.UV2Kind
  19976. * * BABYLON.VertexBuffer.UV3Kind
  19977. * * BABYLON.VertexBuffer.UV4Kind
  19978. * * BABYLON.VertexBuffer.UV5Kind
  19979. * * BABYLON.VertexBuffer.UV6Kind
  19980. * * BABYLON.VertexBuffer.ColorKind
  19981. * * BABYLON.VertexBuffer.MatricesIndicesKind
  19982. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19983. * * BABYLON.VertexBuffer.MatricesWeightsKind
  19984. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19985. * @param data defines the data source
  19986. * @param updatable defines if the data must be flagged as updatable (or static)
  19987. * @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
  19988. * @returns the current mesh
  19989. */
  19990. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19991. return this;
  19992. };
  19993. /**
  19994. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19995. * If the mesh has no geometry, it is simply returned as it is.
  19996. * @param kind defines vertex data kind:
  19997. * * BABYLON.VertexBuffer.PositionKind
  19998. * * BABYLON.VertexBuffer.UVKind
  19999. * * BABYLON.VertexBuffer.UV2Kind
  20000. * * BABYLON.VertexBuffer.UV3Kind
  20001. * * BABYLON.VertexBuffer.UV4Kind
  20002. * * BABYLON.VertexBuffer.UV5Kind
  20003. * * BABYLON.VertexBuffer.UV6Kind
  20004. * * BABYLON.VertexBuffer.ColorKind
  20005. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20006. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20007. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20008. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20009. * @param data defines the data source
  20010. * @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
  20011. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20012. * @returns the current mesh
  20013. */
  20014. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20015. return this;
  20016. };
  20017. /**
  20018. * Sets the mesh indices,
  20019. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20020. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20021. * @param totalVertices Defines the total number of vertices
  20022. * @returns the current mesh
  20023. */
  20024. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20025. return this;
  20026. };
  20027. /**
  20028. * Gets a boolean indicating if specific vertex data is present
  20029. * @param kind defines the vertex data kind to use
  20030. * @returns true is data kind is present
  20031. */
  20032. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20033. return false;
  20034. };
  20035. /**
  20036. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20037. * @returns a BoundingInfo
  20038. */
  20039. AbstractMesh.prototype.getBoundingInfo = function () {
  20040. if (this._masterMesh) {
  20041. return this._masterMesh.getBoundingInfo();
  20042. }
  20043. if (!this._boundingInfo) {
  20044. // this._boundingInfo is being created here
  20045. this._updateBoundingInfo();
  20046. }
  20047. // cannot be null.
  20048. return this._boundingInfo;
  20049. };
  20050. /**
  20051. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20052. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20053. * @returns the current mesh
  20054. */
  20055. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20056. if (includeDescendants === void 0) { includeDescendants = true; }
  20057. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20058. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20059. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20060. if (maxDimension === 0) {
  20061. return this;
  20062. }
  20063. var scale = 1 / maxDimension;
  20064. this.scaling.scaleInPlace(scale);
  20065. return this;
  20066. };
  20067. /**
  20068. * Overwrite the current bounding info
  20069. * @param boundingInfo defines the new bounding info
  20070. * @returns the current mesh
  20071. */
  20072. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20073. this._boundingInfo = boundingInfo;
  20074. return this;
  20075. };
  20076. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20077. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20078. get: function () {
  20079. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20080. },
  20081. enumerable: true,
  20082. configurable: true
  20083. });
  20084. /** @hidden */
  20085. AbstractMesh.prototype._preActivate = function () {
  20086. };
  20087. /** @hidden */
  20088. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20089. };
  20090. /** @hidden */
  20091. AbstractMesh.prototype._activate = function (renderId) {
  20092. this._renderId = renderId;
  20093. };
  20094. /**
  20095. * Gets the current world matrix
  20096. * @returns a Matrix
  20097. */
  20098. AbstractMesh.prototype.getWorldMatrix = function () {
  20099. if (this._masterMesh) {
  20100. return this._masterMesh.getWorldMatrix();
  20101. }
  20102. return _super.prototype.getWorldMatrix.call(this);
  20103. };
  20104. /** @hidden */
  20105. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20106. if (this._masterMesh) {
  20107. return this._masterMesh._getWorldMatrixDeterminant();
  20108. }
  20109. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20110. };
  20111. // ================================== Point of View Movement =================================
  20112. /**
  20113. * Perform relative position change from the point of view of behind the front of the mesh.
  20114. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20115. * Supports definition of mesh facing forward or backward
  20116. * @param amountRight defines the distance on the right axis
  20117. * @param amountUp defines the distance on the up axis
  20118. * @param amountForward defines the distance on the forward axis
  20119. * @returns the current mesh
  20120. */
  20121. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20122. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20123. return this;
  20124. };
  20125. /**
  20126. * Calculate relative position change from the point of view of behind the front of the mesh.
  20127. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20128. * Supports definition of mesh facing forward or backward
  20129. * @param amountRight defines the distance on the right axis
  20130. * @param amountUp defines the distance on the up axis
  20131. * @param amountForward defines the distance on the forward axis
  20132. * @returns the new displacement vector
  20133. */
  20134. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20135. var rotMatrix = new BABYLON.Matrix();
  20136. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20137. rotQuaternion.toRotationMatrix(rotMatrix);
  20138. var translationDelta = BABYLON.Vector3.Zero();
  20139. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20140. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20141. return translationDelta;
  20142. };
  20143. // ================================== Point of View Rotation =================================
  20144. /**
  20145. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20146. * Supports definition of mesh facing forward or backward
  20147. * @param flipBack defines the flip
  20148. * @param twirlClockwise defines the twirl
  20149. * @param tiltRight defines the tilt
  20150. * @returns the current mesh
  20151. */
  20152. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20153. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20154. return this;
  20155. };
  20156. /**
  20157. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20158. * Supports definition of mesh facing forward or backward.
  20159. * @param flipBack defines the flip
  20160. * @param twirlClockwise defines the twirl
  20161. * @param tiltRight defines the tilt
  20162. * @returns the new rotation vector
  20163. */
  20164. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20165. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20166. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20167. };
  20168. /**
  20169. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20170. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20171. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20172. * @returns the new bounding vectors
  20173. */
  20174. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20175. if (includeDescendants === void 0) { includeDescendants = true; }
  20176. if (predicate === void 0) { predicate = null; }
  20177. // Ensures that all world matrix will be recomputed.
  20178. this.getScene().incrementRenderId();
  20179. this.computeWorldMatrix(true);
  20180. var min;
  20181. var max;
  20182. var boundingInfo = this.getBoundingInfo();
  20183. if (!this.subMeshes) {
  20184. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20185. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20186. }
  20187. else {
  20188. min = boundingInfo.boundingBox.minimumWorld;
  20189. max = boundingInfo.boundingBox.maximumWorld;
  20190. }
  20191. if (includeDescendants) {
  20192. var descendants = this.getDescendants(false);
  20193. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20194. var descendant = descendants_1[_i];
  20195. var childMesh = descendant;
  20196. childMesh.computeWorldMatrix(true);
  20197. // Filters meshes based on custom predicate function.
  20198. if (predicate && !predicate(childMesh)) {
  20199. continue;
  20200. }
  20201. //make sure we have the needed params to get mix and max
  20202. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20203. continue;
  20204. }
  20205. var childBoundingInfo = childMesh.getBoundingInfo();
  20206. var boundingBox = childBoundingInfo.boundingBox;
  20207. var minBox = boundingBox.minimumWorld;
  20208. var maxBox = boundingBox.maximumWorld;
  20209. BABYLON.Tools.CheckExtends(minBox, min, max);
  20210. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20211. }
  20212. }
  20213. return {
  20214. min: min,
  20215. max: max
  20216. };
  20217. };
  20218. /** @hidden */
  20219. AbstractMesh.prototype._updateBoundingInfo = function () {
  20220. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20221. this._boundingInfo.update(this.worldMatrixFromCache);
  20222. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20223. return this;
  20224. };
  20225. /** @hidden */
  20226. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20227. if (!this.subMeshes) {
  20228. return this;
  20229. }
  20230. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20231. var subMesh = this.subMeshes[subIndex];
  20232. if (!subMesh.IsGlobal) {
  20233. subMesh.updateBoundingInfo(matrix);
  20234. }
  20235. }
  20236. return this;
  20237. };
  20238. /** @hidden */
  20239. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20240. // Bounding info
  20241. this._updateBoundingInfo();
  20242. };
  20243. /**
  20244. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20245. * A mesh is in the frustum if its bounding box intersects the frustum
  20246. * @param frustumPlanes defines the frustum to test
  20247. * @returns true if the mesh is in the frustum planes
  20248. */
  20249. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20250. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20251. };
  20252. /**
  20253. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20254. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20255. * @param frustumPlanes defines the frustum to test
  20256. * @returns true if the mesh is completely in the frustum planes
  20257. */
  20258. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20259. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20260. };
  20261. /**
  20262. * True if the mesh intersects another mesh or a SolidParticle object
  20263. * @param mesh defines a target mesh or SolidParticle to test
  20264. * @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)
  20265. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20266. * @returns true if there is an intersection
  20267. */
  20268. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20269. if (precise === void 0) { precise = false; }
  20270. if (!this._boundingInfo || !mesh._boundingInfo) {
  20271. return false;
  20272. }
  20273. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20274. return true;
  20275. }
  20276. if (includeDescendants) {
  20277. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20278. var child = _a[_i];
  20279. if (child.intersectsMesh(mesh, precise, true)) {
  20280. return true;
  20281. }
  20282. }
  20283. }
  20284. return false;
  20285. };
  20286. /**
  20287. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20288. * @param point defines the point to test
  20289. * @returns true if there is an intersection
  20290. */
  20291. AbstractMesh.prototype.intersectsPoint = function (point) {
  20292. if (!this._boundingInfo) {
  20293. return false;
  20294. }
  20295. return this._boundingInfo.intersectsPoint(point);
  20296. };
  20297. /**
  20298. * Gets the current physics impostor
  20299. * @see http://doc.babylonjs.com/features/physics_engine
  20300. * @returns a physics impostor or null
  20301. */
  20302. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20303. return this.physicsImpostor;
  20304. };
  20305. /**
  20306. * Gets the position of the current mesh in camera space
  20307. * @param camera defines the camera to use
  20308. * @returns a position
  20309. */
  20310. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20311. if (camera === void 0) { camera = null; }
  20312. if (!camera) {
  20313. camera = this.getScene().activeCamera;
  20314. }
  20315. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20316. };
  20317. /**
  20318. * Returns the distance from the mesh to the active camera
  20319. * @param camera defines the camera to use
  20320. * @returns the distance
  20321. */
  20322. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20323. if (camera === void 0) { camera = null; }
  20324. if (!camera) {
  20325. camera = this.getScene().activeCamera;
  20326. }
  20327. return this.absolutePosition.subtract(camera.position).length();
  20328. };
  20329. /**
  20330. * Apply a physic impulse to the mesh
  20331. * @param force defines the force to apply
  20332. * @param contactPoint defines where to apply the force
  20333. * @returns the current mesh
  20334. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20335. */
  20336. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20337. if (!this.physicsImpostor) {
  20338. return this;
  20339. }
  20340. this.physicsImpostor.applyImpulse(force, contactPoint);
  20341. return this;
  20342. };
  20343. /**
  20344. * Creates a physic joint between two meshes
  20345. * @param otherMesh defines the other mesh to use
  20346. * @param pivot1 defines the pivot to use on this mesh
  20347. * @param pivot2 defines the pivot to use on the other mesh
  20348. * @param options defines additional options (can be plugin dependent)
  20349. * @returns the current mesh
  20350. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20351. */
  20352. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20353. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20354. return this;
  20355. }
  20356. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20357. mainPivot: pivot1,
  20358. connectedPivot: pivot2,
  20359. nativeParams: options
  20360. });
  20361. return this;
  20362. };
  20363. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20364. // Collisions
  20365. /**
  20366. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20367. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20368. */
  20369. get: function () {
  20370. return this._checkCollisions;
  20371. },
  20372. set: function (collisionEnabled) {
  20373. this._checkCollisions = collisionEnabled;
  20374. if (this.getScene().workerCollisions) {
  20375. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20376. }
  20377. },
  20378. enumerable: true,
  20379. configurable: true
  20380. });
  20381. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20382. /**
  20383. * Gets Collider object used to compute collisions (not physics)
  20384. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20385. */
  20386. get: function () {
  20387. return this._collider;
  20388. },
  20389. enumerable: true,
  20390. configurable: true
  20391. });
  20392. /**
  20393. * Move the mesh using collision engine
  20394. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20395. * @param displacement defines the requested displacement vector
  20396. * @returns the current mesh
  20397. */
  20398. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20399. var globalPosition = this.getAbsolutePosition();
  20400. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20401. if (!this._collider) {
  20402. this._collider = new BABYLON.Collider();
  20403. }
  20404. this._collider._radius = this.ellipsoid;
  20405. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20406. return this;
  20407. };
  20408. // Submeshes octree
  20409. /**
  20410. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20411. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20412. * @param maxCapacity defines the maximum size of each block (64 by default)
  20413. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20414. * @returns the new octree
  20415. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20416. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20417. */
  20418. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20419. if (maxCapacity === void 0) { maxCapacity = 64; }
  20420. if (maxDepth === void 0) { maxDepth = 2; }
  20421. if (!this._submeshesOctree) {
  20422. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20423. }
  20424. this.computeWorldMatrix(true);
  20425. var boundingInfo = this.getBoundingInfo();
  20426. // Update octree
  20427. var bbox = boundingInfo.boundingBox;
  20428. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20429. return this._submeshesOctree;
  20430. };
  20431. // Collisions
  20432. /** @hidden */
  20433. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20434. this._generatePointsArray();
  20435. if (!this._positions) {
  20436. return this;
  20437. }
  20438. // Transformation
  20439. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20440. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20441. subMesh._lastColliderWorldVertices = [];
  20442. subMesh._trianglePlanes = [];
  20443. var start = subMesh.verticesStart;
  20444. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20445. for (var i = start; i < end; i++) {
  20446. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20447. }
  20448. }
  20449. // Collide
  20450. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20451. if (collider.collisionFound) {
  20452. collider.collidedMesh = this;
  20453. }
  20454. return this;
  20455. };
  20456. /** @hidden */
  20457. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20458. var subMeshes;
  20459. var len;
  20460. // Octrees
  20461. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20462. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20463. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20464. len = intersections.length;
  20465. subMeshes = intersections.data;
  20466. }
  20467. else {
  20468. subMeshes = this.subMeshes;
  20469. len = subMeshes.length;
  20470. }
  20471. for (var index = 0; index < len; index++) {
  20472. var subMesh = subMeshes[index];
  20473. // Bounding test
  20474. if (len > 1 && !subMesh._checkCollision(collider))
  20475. continue;
  20476. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20477. }
  20478. return this;
  20479. };
  20480. /** @hidden */
  20481. AbstractMesh.prototype._checkCollision = function (collider) {
  20482. // Bounding box test
  20483. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20484. return this;
  20485. // Transformation matrix
  20486. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20487. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20488. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20489. return this;
  20490. };
  20491. // Picking
  20492. /** @hidden */
  20493. AbstractMesh.prototype._generatePointsArray = function () {
  20494. return false;
  20495. };
  20496. /**
  20497. * Checks if the passed Ray intersects with the mesh
  20498. * @param ray defines the ray to use
  20499. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20500. * @returns the picking info
  20501. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20502. */
  20503. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20504. var pickingInfo = new BABYLON.PickingInfo();
  20505. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20506. return pickingInfo;
  20507. }
  20508. if (!this._generatePointsArray()) {
  20509. return pickingInfo;
  20510. }
  20511. var intersectInfo = null;
  20512. // Octrees
  20513. var subMeshes;
  20514. var len;
  20515. if (this._submeshesOctree && this.useOctreeForPicking) {
  20516. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20517. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20518. len = intersections.length;
  20519. subMeshes = intersections.data;
  20520. }
  20521. else {
  20522. subMeshes = this.subMeshes;
  20523. len = subMeshes.length;
  20524. }
  20525. for (var index = 0; index < len; index++) {
  20526. var subMesh = subMeshes[index];
  20527. // Bounding test
  20528. if (len > 1 && !subMesh.canIntersects(ray))
  20529. continue;
  20530. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20531. if (currentIntersectInfo) {
  20532. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20533. intersectInfo = currentIntersectInfo;
  20534. intersectInfo.subMeshId = index;
  20535. if (fastCheck) {
  20536. break;
  20537. }
  20538. }
  20539. }
  20540. }
  20541. if (intersectInfo) {
  20542. // Get picked point
  20543. var world = this.getWorldMatrix();
  20544. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20545. var direction = ray.direction.clone();
  20546. direction = direction.scale(intersectInfo.distance);
  20547. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20548. var pickedPoint = worldOrigin.add(worldDirection);
  20549. // Return result
  20550. pickingInfo.hit = true;
  20551. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20552. pickingInfo.pickedPoint = pickedPoint;
  20553. pickingInfo.pickedMesh = this;
  20554. pickingInfo.bu = intersectInfo.bu || 0;
  20555. pickingInfo.bv = intersectInfo.bv || 0;
  20556. pickingInfo.faceId = intersectInfo.faceId;
  20557. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20558. return pickingInfo;
  20559. }
  20560. return pickingInfo;
  20561. };
  20562. /**
  20563. * Clones the current mesh
  20564. * @param name defines the mesh name
  20565. * @param newParent defines the new mesh parent
  20566. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20567. * @returns the new mesh
  20568. */
  20569. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20570. return null;
  20571. };
  20572. /**
  20573. * Disposes all the submeshes of the current meshnp
  20574. * @returns the current mesh
  20575. */
  20576. AbstractMesh.prototype.releaseSubMeshes = function () {
  20577. if (this.subMeshes) {
  20578. while (this.subMeshes.length) {
  20579. this.subMeshes[0].dispose();
  20580. }
  20581. }
  20582. else {
  20583. this.subMeshes = new Array();
  20584. }
  20585. return this;
  20586. };
  20587. /**
  20588. * Releases resources associated with this abstract mesh.
  20589. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20590. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20591. */
  20592. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20593. var _this = this;
  20594. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20595. var index;
  20596. // Smart Array Retainers.
  20597. this.getScene().freeActiveMeshes();
  20598. this.getScene().freeRenderingGroups();
  20599. // Action manager
  20600. if (this.actionManager !== undefined && this.actionManager !== null) {
  20601. this.actionManager.dispose();
  20602. this.actionManager = null;
  20603. }
  20604. // Skeleton
  20605. this._skeleton = null;
  20606. // Physics
  20607. if (this.physicsImpostor) {
  20608. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20609. }
  20610. // Intersections in progress
  20611. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20612. var other = this._intersectionsInProgress[index];
  20613. var pos = other._intersectionsInProgress.indexOf(this);
  20614. other._intersectionsInProgress.splice(pos, 1);
  20615. }
  20616. this._intersectionsInProgress = [];
  20617. // Lights
  20618. var lights = this.getScene().lights;
  20619. lights.forEach(function (light) {
  20620. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20621. if (meshIndex !== -1) {
  20622. light.includedOnlyMeshes.splice(meshIndex, 1);
  20623. }
  20624. meshIndex = light.excludedMeshes.indexOf(_this);
  20625. if (meshIndex !== -1) {
  20626. light.excludedMeshes.splice(meshIndex, 1);
  20627. }
  20628. // Shadow generators
  20629. var generator = light.getShadowGenerator();
  20630. if (generator) {
  20631. var shadowMap = generator.getShadowMap();
  20632. if (shadowMap && shadowMap.renderList) {
  20633. meshIndex = shadowMap.renderList.indexOf(_this);
  20634. if (meshIndex !== -1) {
  20635. shadowMap.renderList.splice(meshIndex, 1);
  20636. }
  20637. }
  20638. }
  20639. });
  20640. // Edges
  20641. if (this._edgesRenderer) {
  20642. this._edgesRenderer.dispose();
  20643. this._edgesRenderer = null;
  20644. }
  20645. // SubMeshes
  20646. if (this.getClassName() !== "InstancedMesh") {
  20647. this.releaseSubMeshes();
  20648. }
  20649. // Octree
  20650. var sceneOctree = this.getScene().selectionOctree;
  20651. if (sceneOctree !== undefined && sceneOctree !== null) {
  20652. var index = sceneOctree.dynamicContent.indexOf(this);
  20653. if (index !== -1) {
  20654. sceneOctree.dynamicContent.splice(index, 1);
  20655. }
  20656. }
  20657. // Query
  20658. var engine = this.getScene().getEngine();
  20659. if (this._occlusionQuery) {
  20660. this._isOcclusionQueryInProgress = false;
  20661. engine.deleteQuery(this._occlusionQuery);
  20662. this._occlusionQuery = null;
  20663. }
  20664. // Engine
  20665. engine.wipeCaches();
  20666. // Remove from scene
  20667. this.getScene().removeMesh(this);
  20668. if (disposeMaterialAndTextures) {
  20669. if (this.material) {
  20670. this.material.dispose(false, true);
  20671. }
  20672. }
  20673. if (!doNotRecurse) {
  20674. // Particles
  20675. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20676. if (this.getScene().particleSystems[index].emitter === this) {
  20677. this.getScene().particleSystems[index].dispose();
  20678. index--;
  20679. }
  20680. }
  20681. }
  20682. // facet data
  20683. if (this._facetDataEnabled) {
  20684. this.disableFacetData();
  20685. }
  20686. this.onAfterWorldMatrixUpdateObservable.clear();
  20687. this.onCollideObservable.clear();
  20688. this.onCollisionPositionChangeObservable.clear();
  20689. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20690. };
  20691. /**
  20692. * Adds the passed mesh as a child to the current mesh
  20693. * @param mesh defines the child mesh
  20694. * @returns the current mesh
  20695. */
  20696. AbstractMesh.prototype.addChild = function (mesh) {
  20697. mesh.setParent(this);
  20698. return this;
  20699. };
  20700. /**
  20701. * Removes the passed mesh from the current mesh children list
  20702. * @param mesh defines the child mesh
  20703. * @returns the current mesh
  20704. */
  20705. AbstractMesh.prototype.removeChild = function (mesh) {
  20706. mesh.setParent(null);
  20707. return this;
  20708. };
  20709. // Facet data
  20710. /** @hidden */
  20711. AbstractMesh.prototype._initFacetData = function () {
  20712. if (!this._facetNormals) {
  20713. this._facetNormals = new Array();
  20714. }
  20715. if (!this._facetPositions) {
  20716. this._facetPositions = new Array();
  20717. }
  20718. if (!this._facetPartitioning) {
  20719. this._facetPartitioning = new Array();
  20720. }
  20721. this._facetNb = (this.getIndices().length / 3) | 0;
  20722. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20723. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20724. for (var f = 0; f < this._facetNb; f++) {
  20725. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20726. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20727. }
  20728. this._facetDataEnabled = true;
  20729. return this;
  20730. };
  20731. /**
  20732. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20733. * This method can be called within the render loop.
  20734. * 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
  20735. * @returns the current mesh
  20736. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20737. */
  20738. AbstractMesh.prototype.updateFacetData = function () {
  20739. if (!this._facetDataEnabled) {
  20740. this._initFacetData();
  20741. }
  20742. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20743. var indices = this.getIndices();
  20744. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20745. var bInfo = this.getBoundingInfo();
  20746. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20747. // init arrays, matrix and sort function on first call
  20748. this._facetDepthSortEnabled = true;
  20749. if (indices instanceof Uint16Array) {
  20750. this._depthSortedIndices = new Uint16Array(indices);
  20751. }
  20752. else if (indices instanceof Uint32Array) {
  20753. this._depthSortedIndices = new Uint32Array(indices);
  20754. }
  20755. else {
  20756. var needs32bits = false;
  20757. for (var i = 0; i < indices.length; i++) {
  20758. if (indices[i] > 65535) {
  20759. needs32bits = true;
  20760. break;
  20761. }
  20762. }
  20763. if (needs32bits) {
  20764. this._depthSortedIndices = new Uint32Array(indices);
  20765. }
  20766. else {
  20767. this._depthSortedIndices = new Uint16Array(indices);
  20768. }
  20769. }
  20770. this._facetDepthSortFunction = function (f1, f2) {
  20771. return (f2.sqDistance - f1.sqDistance);
  20772. };
  20773. if (!this._facetDepthSortFrom) {
  20774. var camera = this.getScene().activeCamera;
  20775. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20776. }
  20777. this._depthSortedFacets = [];
  20778. for (var f = 0; f < this._facetNb; f++) {
  20779. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20780. this._depthSortedFacets.push(depthSortedFacet);
  20781. }
  20782. this._invertedMatrix = BABYLON.Matrix.Identity();
  20783. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20784. }
  20785. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20786. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20787. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20788. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20789. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20790. this._subDiv.max = this._partitioningSubdivisions;
  20791. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20792. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20793. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20794. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20795. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20796. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20797. // set the parameters for ComputeNormals()
  20798. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20799. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20800. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20801. this._facetParameters.bInfo = bInfo;
  20802. this._facetParameters.bbSize = this._bbSize;
  20803. this._facetParameters.subDiv = this._subDiv;
  20804. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20805. this._facetParameters.depthSort = this._facetDepthSort;
  20806. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20807. this.computeWorldMatrix(true);
  20808. this._worldMatrix.invertToRef(this._invertedMatrix);
  20809. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20810. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20811. }
  20812. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20813. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20814. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20815. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20816. var l = (this._depthSortedIndices.length / 3) | 0;
  20817. for (var f = 0; f < l; f++) {
  20818. var sind = this._depthSortedFacets[f].ind;
  20819. this._depthSortedIndices[f * 3] = indices[sind];
  20820. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20821. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20822. }
  20823. this.updateIndices(this._depthSortedIndices);
  20824. }
  20825. return this;
  20826. };
  20827. /**
  20828. * Returns the facetLocalNormals array.
  20829. * The normals are expressed in the mesh local spac
  20830. * @returns an array of Vector3
  20831. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20832. */
  20833. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20834. if (!this._facetNormals) {
  20835. this.updateFacetData();
  20836. }
  20837. return this._facetNormals;
  20838. };
  20839. /**
  20840. * Returns the facetLocalPositions array.
  20841. * The facet positions are expressed in the mesh local space
  20842. * @returns an array of Vector3
  20843. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20844. */
  20845. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20846. if (!this._facetPositions) {
  20847. this.updateFacetData();
  20848. }
  20849. return this._facetPositions;
  20850. };
  20851. /**
  20852. * Returns the facetLocalPartioning array
  20853. * @returns an array of array of numbers
  20854. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20855. */
  20856. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20857. if (!this._facetPartitioning) {
  20858. this.updateFacetData();
  20859. }
  20860. return this._facetPartitioning;
  20861. };
  20862. /**
  20863. * Returns the i-th facet position in the world system.
  20864. * This method allocates a new Vector3 per call
  20865. * @param i defines the facet index
  20866. * @returns a new Vector3
  20867. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20868. */
  20869. AbstractMesh.prototype.getFacetPosition = function (i) {
  20870. var pos = BABYLON.Vector3.Zero();
  20871. this.getFacetPositionToRef(i, pos);
  20872. return pos;
  20873. };
  20874. /**
  20875. * Sets the reference Vector3 with the i-th facet position in the world system
  20876. * @param i defines the facet index
  20877. * @param ref defines the target vector
  20878. * @returns the current mesh
  20879. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20880. */
  20881. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20882. var localPos = (this.getFacetLocalPositions())[i];
  20883. var world = this.getWorldMatrix();
  20884. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20885. return this;
  20886. };
  20887. /**
  20888. * Returns the i-th facet normal in the world system.
  20889. * This method allocates a new Vector3 per call
  20890. * @param i defines the facet index
  20891. * @returns a new Vector3
  20892. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20893. */
  20894. AbstractMesh.prototype.getFacetNormal = function (i) {
  20895. var norm = BABYLON.Vector3.Zero();
  20896. this.getFacetNormalToRef(i, norm);
  20897. return norm;
  20898. };
  20899. /**
  20900. * Sets the reference Vector3 with the i-th facet normal in the world system
  20901. * @param i defines the facet index
  20902. * @param ref defines the target vector
  20903. * @returns the current mesh
  20904. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20905. */
  20906. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20907. var localNorm = (this.getFacetLocalNormals())[i];
  20908. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20909. return this;
  20910. };
  20911. /**
  20912. * 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)
  20913. * @param x defines x coordinate
  20914. * @param y defines y coordinate
  20915. * @param z defines z coordinate
  20916. * @returns the array of facet indexes
  20917. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20918. */
  20919. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20920. var bInfo = this.getBoundingInfo();
  20921. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20922. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20923. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20924. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20925. return null;
  20926. }
  20927. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20928. };
  20929. /**
  20930. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20931. * @param projected sets as the (x,y,z) world projection on the facet
  20932. * @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
  20933. * @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
  20934. * @param x defines x coordinate
  20935. * @param y defines y coordinate
  20936. * @param z defines z coordinate
  20937. * @returns the face index if found (or null instead)
  20938. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20939. */
  20940. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20941. if (checkFace === void 0) { checkFace = false; }
  20942. if (facing === void 0) { facing = true; }
  20943. var world = this.getWorldMatrix();
  20944. var invMat = BABYLON.Tmp.Matrix[5];
  20945. world.invertToRef(invMat);
  20946. var invVect = BABYLON.Tmp.Vector3[8];
  20947. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20948. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20949. if (projected) {
  20950. // tranform the local computed projected vector to world coordinates
  20951. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20952. }
  20953. return closest;
  20954. };
  20955. /**
  20956. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  20957. * @param projected sets as the (x,y,z) local projection on the facet
  20958. * @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
  20959. * @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
  20960. * @param x defines x coordinate
  20961. * @param y defines y coordinate
  20962. * @param z defines z coordinate
  20963. * @returns the face index if found (or null instead)
  20964. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20965. */
  20966. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20967. if (checkFace === void 0) { checkFace = false; }
  20968. if (facing === void 0) { facing = true; }
  20969. var closest = null;
  20970. var tmpx = 0.0;
  20971. var tmpy = 0.0;
  20972. var tmpz = 0.0;
  20973. var d = 0.0; // tmp dot facet normal * facet position
  20974. var t0 = 0.0;
  20975. var projx = 0.0;
  20976. var projy = 0.0;
  20977. var projz = 0.0;
  20978. // Get all the facets in the same partitioning block than (x, y, z)
  20979. var facetPositions = this.getFacetLocalPositions();
  20980. var facetNormals = this.getFacetLocalNormals();
  20981. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20982. if (!facetsInBlock) {
  20983. return null;
  20984. }
  20985. // Get the closest facet to (x, y, z)
  20986. var shortest = Number.MAX_VALUE; // init distance vars
  20987. var tmpDistance = shortest;
  20988. var fib; // current facet in the block
  20989. var norm; // current facet normal
  20990. var p0; // current facet barycenter position
  20991. // loop on all the facets in the current partitioning block
  20992. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20993. fib = facetsInBlock[idx];
  20994. norm = facetNormals[fib];
  20995. p0 = facetPositions[fib];
  20996. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20997. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20998. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20999. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21000. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21001. projx = x + norm.x * t0;
  21002. projy = y + norm.y * t0;
  21003. projz = z + norm.z * t0;
  21004. tmpx = projx - x;
  21005. tmpy = projy - y;
  21006. tmpz = projz - z;
  21007. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21008. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21009. shortest = tmpDistance;
  21010. closest = fib;
  21011. if (projected) {
  21012. projected.x = projx;
  21013. projected.y = projy;
  21014. projected.z = projz;
  21015. }
  21016. }
  21017. }
  21018. }
  21019. return closest;
  21020. };
  21021. /**
  21022. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21023. * @returns the parameters
  21024. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21025. */
  21026. AbstractMesh.prototype.getFacetDataParameters = function () {
  21027. return this._facetParameters;
  21028. };
  21029. /**
  21030. * Disables the feature FacetData and frees the related memory
  21031. * @returns the current mesh
  21032. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21033. */
  21034. AbstractMesh.prototype.disableFacetData = function () {
  21035. if (this._facetDataEnabled) {
  21036. this._facetDataEnabled = false;
  21037. this._facetPositions = new Array();
  21038. this._facetNormals = new Array();
  21039. this._facetPartitioning = new Array();
  21040. this._facetParameters = null;
  21041. this._depthSortedIndices = new Uint32Array(0);
  21042. }
  21043. return this;
  21044. };
  21045. /**
  21046. * Updates the AbstractMesh indices array
  21047. * @param indices defines the data source
  21048. * @returns the current mesh
  21049. */
  21050. AbstractMesh.prototype.updateIndices = function (indices) {
  21051. return this;
  21052. };
  21053. /**
  21054. * Creates new normals data for the mesh
  21055. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21056. * @returns the current mesh
  21057. */
  21058. AbstractMesh.prototype.createNormals = function (updatable) {
  21059. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21060. var indices = this.getIndices();
  21061. var normals;
  21062. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21063. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21064. }
  21065. else {
  21066. normals = [];
  21067. }
  21068. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21069. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21070. return this;
  21071. };
  21072. /**
  21073. * Align the mesh with a normal
  21074. * @param normal defines the normal to use
  21075. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21076. * @returns the current mesh
  21077. */
  21078. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21079. if (!upDirection) {
  21080. upDirection = BABYLON.Axis.Y;
  21081. }
  21082. var axisX = BABYLON.Tmp.Vector3[0];
  21083. var axisZ = BABYLON.Tmp.Vector3[1];
  21084. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21085. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21086. if (this.rotationQuaternion) {
  21087. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21088. }
  21089. else {
  21090. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21091. }
  21092. return this;
  21093. };
  21094. /** @hidden */
  21095. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21096. this._isOccluded = false;
  21097. };
  21098. /** No occlusion */
  21099. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21100. /** Occlusion set to optimisitic */
  21101. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21102. /** Occlusion set to strict */
  21103. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21104. /** Use an accurante occlusion algorithm */
  21105. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21106. /** Use a conservative occlusion algorithm */
  21107. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21108. return AbstractMesh;
  21109. }(BABYLON.TransformNode));
  21110. BABYLON.AbstractMesh = AbstractMesh;
  21111. })(BABYLON || (BABYLON = {}));
  21112. //# sourceMappingURL=babylon.abstractMesh.js.map
  21113. var BABYLON;
  21114. (function (BABYLON) {
  21115. /**
  21116. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21117. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21118. * 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.
  21119. */
  21120. var Light = /** @class */ (function (_super) {
  21121. __extends(Light, _super);
  21122. /**
  21123. * Creates a Light object in the scene.
  21124. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21125. * @param name The firendly name of the light
  21126. * @param scene The scene the light belongs too
  21127. */
  21128. function Light(name, scene) {
  21129. var _this = _super.call(this, name, scene) || this;
  21130. /**
  21131. * Diffuse gives the basic color to an object.
  21132. */
  21133. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21134. /**
  21135. * Specular produces a highlight color on an object.
  21136. * Note: This is note affecting PBR materials.
  21137. */
  21138. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21139. /**
  21140. * Strength of the light.
  21141. * Note: By default it is define in the framework own unit.
  21142. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21143. */
  21144. _this.intensity = 1.0;
  21145. /**
  21146. * Defines how far from the source the light is impacting in scene units.
  21147. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21148. */
  21149. _this.range = Number.MAX_VALUE;
  21150. /**
  21151. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21152. * of light.
  21153. */
  21154. _this._photometricScale = 1.0;
  21155. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21156. _this._radius = 0.00001;
  21157. /**
  21158. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21159. * exceeding the number allowed of the materials.
  21160. */
  21161. _this.renderPriority = 0;
  21162. _this._shadowEnabled = true;
  21163. _this._excludeWithLayerMask = 0;
  21164. _this._includeOnlyWithLayerMask = 0;
  21165. _this._lightmapMode = 0;
  21166. /**
  21167. * @hidden Internal use only.
  21168. */
  21169. _this._excludedMeshesIds = new Array();
  21170. /**
  21171. * @hidden Internal use only.
  21172. */
  21173. _this._includedOnlyMeshesIds = new Array();
  21174. _this.getScene().addLight(_this);
  21175. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21176. _this._buildUniformLayout();
  21177. _this.includedOnlyMeshes = new Array();
  21178. _this.excludedMeshes = new Array();
  21179. _this._resyncMeshes();
  21180. return _this;
  21181. }
  21182. Object.defineProperty(Light.prototype, "intensityMode", {
  21183. /**
  21184. * Gets the photometric scale used to interpret the intensity.
  21185. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21186. */
  21187. get: function () {
  21188. return this._intensityMode;
  21189. },
  21190. /**
  21191. * Sets the photometric scale used to interpret the intensity.
  21192. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21193. */
  21194. set: function (value) {
  21195. this._intensityMode = value;
  21196. this._computePhotometricScale();
  21197. },
  21198. enumerable: true,
  21199. configurable: true
  21200. });
  21201. ;
  21202. ;
  21203. Object.defineProperty(Light.prototype, "radius", {
  21204. /**
  21205. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21206. */
  21207. get: function () {
  21208. return this._radius;
  21209. },
  21210. /**
  21211. * sets the light radius used by PBR Materials to simulate soft area lights.
  21212. */
  21213. set: function (value) {
  21214. this._radius = value;
  21215. this._computePhotometricScale();
  21216. },
  21217. enumerable: true,
  21218. configurable: true
  21219. });
  21220. ;
  21221. ;
  21222. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21223. /**
  21224. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21225. * the current shadow generator.
  21226. */
  21227. get: function () {
  21228. return this._shadowEnabled;
  21229. },
  21230. /**
  21231. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21232. * the current shadow generator.
  21233. */
  21234. set: function (value) {
  21235. if (this._shadowEnabled === value) {
  21236. return;
  21237. }
  21238. this._shadowEnabled = value;
  21239. this._markMeshesAsLightDirty();
  21240. },
  21241. enumerable: true,
  21242. configurable: true
  21243. });
  21244. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21245. /**
  21246. * Gets the only meshes impacted by this light.
  21247. */
  21248. get: function () {
  21249. return this._includedOnlyMeshes;
  21250. },
  21251. /**
  21252. * Sets the only meshes impacted by this light.
  21253. */
  21254. set: function (value) {
  21255. this._includedOnlyMeshes = value;
  21256. this._hookArrayForIncludedOnly(value);
  21257. },
  21258. enumerable: true,
  21259. configurable: true
  21260. });
  21261. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21262. /**
  21263. * Gets the meshes not impacted by this light.
  21264. */
  21265. get: function () {
  21266. return this._excludedMeshes;
  21267. },
  21268. /**
  21269. * Sets the meshes not impacted by this light.
  21270. */
  21271. set: function (value) {
  21272. this._excludedMeshes = value;
  21273. this._hookArrayForExcluded(value);
  21274. },
  21275. enumerable: true,
  21276. configurable: true
  21277. });
  21278. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21279. /**
  21280. * Gets the layer id use to find what meshes are not impacted by the light.
  21281. * Inactive if 0
  21282. */
  21283. get: function () {
  21284. return this._excludeWithLayerMask;
  21285. },
  21286. /**
  21287. * Sets the layer id use to find what meshes are not impacted by the light.
  21288. * Inactive if 0
  21289. */
  21290. set: function (value) {
  21291. this._excludeWithLayerMask = value;
  21292. this._resyncMeshes();
  21293. },
  21294. enumerable: true,
  21295. configurable: true
  21296. });
  21297. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21298. /**
  21299. * Gets the layer id use to find what meshes are impacted by the light.
  21300. * Inactive if 0
  21301. */
  21302. get: function () {
  21303. return this._includeOnlyWithLayerMask;
  21304. },
  21305. /**
  21306. * Sets the layer id use to find what meshes are impacted by the light.
  21307. * Inactive if 0
  21308. */
  21309. set: function (value) {
  21310. this._includeOnlyWithLayerMask = value;
  21311. this._resyncMeshes();
  21312. },
  21313. enumerable: true,
  21314. configurable: true
  21315. });
  21316. Object.defineProperty(Light.prototype, "lightmapMode", {
  21317. /**
  21318. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21319. */
  21320. get: function () {
  21321. return this._lightmapMode;
  21322. },
  21323. /**
  21324. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21325. */
  21326. set: function (value) {
  21327. if (this._lightmapMode === value) {
  21328. return;
  21329. }
  21330. this._lightmapMode = value;
  21331. this._markMeshesAsLightDirty();
  21332. },
  21333. enumerable: true,
  21334. configurable: true
  21335. });
  21336. /**
  21337. * Returns the string "Light".
  21338. * @returns the class name
  21339. */
  21340. Light.prototype.getClassName = function () {
  21341. return "Light";
  21342. };
  21343. /**
  21344. * Converts the light information to a readable string for debug purpose.
  21345. * @param fullDetails Supports for multiple levels of logging within scene loading
  21346. * @returns the human readable light info
  21347. */
  21348. Light.prototype.toString = function (fullDetails) {
  21349. var ret = "Name: " + this.name;
  21350. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21351. if (this.animations) {
  21352. for (var i = 0; i < this.animations.length; i++) {
  21353. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21354. }
  21355. }
  21356. if (fullDetails) {
  21357. }
  21358. return ret;
  21359. };
  21360. /**
  21361. * Set the enabled state of this node.
  21362. * @param value - the new enabled state
  21363. */
  21364. Light.prototype.setEnabled = function (value) {
  21365. _super.prototype.setEnabled.call(this, value);
  21366. this._resyncMeshes();
  21367. };
  21368. /**
  21369. * Returns the Light associated shadow generator if any.
  21370. * @return the associated shadow generator.
  21371. */
  21372. Light.prototype.getShadowGenerator = function () {
  21373. return this._shadowGenerator;
  21374. };
  21375. /**
  21376. * Returns a Vector3, the absolute light position in the World.
  21377. * @returns the world space position of the light
  21378. */
  21379. Light.prototype.getAbsolutePosition = function () {
  21380. return BABYLON.Vector3.Zero();
  21381. };
  21382. /**
  21383. * Specifies if the light will affect the passed mesh.
  21384. * @param mesh The mesh to test against the light
  21385. * @return true the mesh is affected otherwise, false.
  21386. */
  21387. Light.prototype.canAffectMesh = function (mesh) {
  21388. if (!mesh) {
  21389. return true;
  21390. }
  21391. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21392. return false;
  21393. }
  21394. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21395. return false;
  21396. }
  21397. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21398. return false;
  21399. }
  21400. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21401. return false;
  21402. }
  21403. return true;
  21404. };
  21405. /**
  21406. * Computes and Returns the light World matrix.
  21407. * @returns the world matrix
  21408. */
  21409. Light.prototype.getWorldMatrix = function () {
  21410. this._currentRenderId = this.getScene().getRenderId();
  21411. this._childRenderId = this._currentRenderId;
  21412. var worldMatrix = this._getWorldMatrix();
  21413. if (this.parent && this.parent.getWorldMatrix) {
  21414. if (!this._parentedWorldMatrix) {
  21415. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21416. }
  21417. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21418. this._markSyncedWithParent();
  21419. return this._parentedWorldMatrix;
  21420. }
  21421. return worldMatrix;
  21422. };
  21423. /**
  21424. * Sort function to order lights for rendering.
  21425. * @param a First Light object to compare to second.
  21426. * @param b Second Light object to compare first.
  21427. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21428. */
  21429. Light.CompareLightsPriority = function (a, b) {
  21430. //shadow-casting lights have priority over non-shadow-casting lights
  21431. //the renderPrioirty is a secondary sort criterion
  21432. if (a.shadowEnabled !== b.shadowEnabled) {
  21433. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21434. }
  21435. return b.renderPriority - a.renderPriority;
  21436. };
  21437. /**
  21438. * Releases resources associated with this node.
  21439. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21440. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21441. */
  21442. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21443. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21444. if (this._shadowGenerator) {
  21445. this._shadowGenerator.dispose();
  21446. this._shadowGenerator = null;
  21447. }
  21448. // Animations
  21449. this.getScene().stopAnimation(this);
  21450. // Remove from meshes
  21451. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21452. var mesh = _a[_i];
  21453. mesh._removeLightSource(this);
  21454. }
  21455. this._uniformBuffer.dispose();
  21456. // Remove from scene
  21457. this.getScene().removeLight(this);
  21458. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21459. };
  21460. /**
  21461. * Returns the light type ID (integer).
  21462. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21463. */
  21464. Light.prototype.getTypeID = function () {
  21465. return 0;
  21466. };
  21467. /**
  21468. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21469. * @returns the scaled intensity in intensity mode unit
  21470. */
  21471. Light.prototype.getScaledIntensity = function () {
  21472. return this._photometricScale * this.intensity;
  21473. };
  21474. /**
  21475. * Returns a new Light object, named "name", from the current one.
  21476. * @param name The name of the cloned light
  21477. * @returns the new created light
  21478. */
  21479. Light.prototype.clone = function (name) {
  21480. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21481. if (!constructor) {
  21482. return null;
  21483. }
  21484. return BABYLON.SerializationHelper.Clone(constructor, this);
  21485. };
  21486. /**
  21487. * Serializes the current light into a Serialization object.
  21488. * @returns the serialized object.
  21489. */
  21490. Light.prototype.serialize = function () {
  21491. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21492. // Type
  21493. serializationObject.type = this.getTypeID();
  21494. // Parent
  21495. if (this.parent) {
  21496. serializationObject.parentId = this.parent.id;
  21497. }
  21498. // Inclusion / exclusions
  21499. if (this.excludedMeshes.length > 0) {
  21500. serializationObject.excludedMeshesIds = [];
  21501. this.excludedMeshes.forEach(function (mesh) {
  21502. serializationObject.excludedMeshesIds.push(mesh.id);
  21503. });
  21504. }
  21505. if (this.includedOnlyMeshes.length > 0) {
  21506. serializationObject.includedOnlyMeshesIds = [];
  21507. this.includedOnlyMeshes.forEach(function (mesh) {
  21508. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21509. });
  21510. }
  21511. // Animations
  21512. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21513. serializationObject.ranges = this.serializeAnimationRanges();
  21514. return serializationObject;
  21515. };
  21516. /**
  21517. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21518. * This new light is named "name" and added to the passed scene.
  21519. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21520. * @param name The friendly name of the light
  21521. * @param scene The scene the new light will belong to
  21522. * @returns the constructor function
  21523. */
  21524. Light.GetConstructorFromName = function (type, name, scene) {
  21525. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21526. if (constructorFunc) {
  21527. return constructorFunc;
  21528. }
  21529. // Default to no light for none present once.
  21530. return null;
  21531. };
  21532. /**
  21533. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21534. * @param parsedLight The JSON representation of the light
  21535. * @param scene The scene to create the parsed light in
  21536. * @returns the created light after parsing
  21537. */
  21538. Light.Parse = function (parsedLight, scene) {
  21539. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21540. if (!constructor) {
  21541. return null;
  21542. }
  21543. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21544. // Inclusion / exclusions
  21545. if (parsedLight.excludedMeshesIds) {
  21546. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21547. }
  21548. if (parsedLight.includedOnlyMeshesIds) {
  21549. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21550. }
  21551. // Parent
  21552. if (parsedLight.parentId) {
  21553. light._waitingParentId = parsedLight.parentId;
  21554. }
  21555. // Animations
  21556. if (parsedLight.animations) {
  21557. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21558. var parsedAnimation = parsedLight.animations[animationIndex];
  21559. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21560. }
  21561. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21562. }
  21563. if (parsedLight.autoAnimate) {
  21564. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21565. }
  21566. return light;
  21567. };
  21568. Light.prototype._hookArrayForExcluded = function (array) {
  21569. var _this = this;
  21570. var oldPush = array.push;
  21571. array.push = function () {
  21572. var items = [];
  21573. for (var _i = 0; _i < arguments.length; _i++) {
  21574. items[_i] = arguments[_i];
  21575. }
  21576. var result = oldPush.apply(array, items);
  21577. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21578. var item = items_1[_a];
  21579. item._resyncLighSource(_this);
  21580. }
  21581. return result;
  21582. };
  21583. var oldSplice = array.splice;
  21584. array.splice = function (index, deleteCount) {
  21585. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21586. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21587. var item = deleted_1[_i];
  21588. item._resyncLighSource(_this);
  21589. }
  21590. return deleted;
  21591. };
  21592. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21593. var item = array_1[_i];
  21594. item._resyncLighSource(this);
  21595. }
  21596. };
  21597. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21598. var _this = this;
  21599. var oldPush = array.push;
  21600. array.push = function () {
  21601. var items = [];
  21602. for (var _i = 0; _i < arguments.length; _i++) {
  21603. items[_i] = arguments[_i];
  21604. }
  21605. var result = oldPush.apply(array, items);
  21606. _this._resyncMeshes();
  21607. return result;
  21608. };
  21609. var oldSplice = array.splice;
  21610. array.splice = function (index, deleteCount) {
  21611. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21612. _this._resyncMeshes();
  21613. return deleted;
  21614. };
  21615. this._resyncMeshes();
  21616. };
  21617. Light.prototype._resyncMeshes = function () {
  21618. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21619. var mesh = _a[_i];
  21620. mesh._resyncLighSource(this);
  21621. }
  21622. };
  21623. /**
  21624. * Forces the meshes to update their light related information in their rendering used effects
  21625. * @hidden Internal Use Only
  21626. */
  21627. Light.prototype._markMeshesAsLightDirty = function () {
  21628. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21629. var mesh = _a[_i];
  21630. if (mesh._lightSources.indexOf(this) !== -1) {
  21631. mesh._markSubMeshesAsLightDirty();
  21632. }
  21633. }
  21634. };
  21635. /**
  21636. * Recomputes the cached photometric scale if needed.
  21637. */
  21638. Light.prototype._computePhotometricScale = function () {
  21639. this._photometricScale = this._getPhotometricScale();
  21640. this.getScene().resetCachedMaterial();
  21641. };
  21642. /**
  21643. * Returns the Photometric Scale according to the light type and intensity mode.
  21644. */
  21645. Light.prototype._getPhotometricScale = function () {
  21646. var photometricScale = 0.0;
  21647. var lightTypeID = this.getTypeID();
  21648. //get photometric mode
  21649. var photometricMode = this.intensityMode;
  21650. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21651. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21652. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21653. }
  21654. else {
  21655. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21656. }
  21657. }
  21658. //compute photometric scale
  21659. switch (lightTypeID) {
  21660. case Light.LIGHTTYPEID_POINTLIGHT:
  21661. case Light.LIGHTTYPEID_SPOTLIGHT:
  21662. switch (photometricMode) {
  21663. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21664. photometricScale = 1.0 / (4.0 * Math.PI);
  21665. break;
  21666. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21667. photometricScale = 1.0;
  21668. break;
  21669. case Light.INTENSITYMODE_LUMINANCE:
  21670. photometricScale = this.radius * this.radius;
  21671. break;
  21672. }
  21673. break;
  21674. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21675. switch (photometricMode) {
  21676. case Light.INTENSITYMODE_ILLUMINANCE:
  21677. photometricScale = 1.0;
  21678. break;
  21679. case Light.INTENSITYMODE_LUMINANCE:
  21680. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21681. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21682. var apexAngleRadians = this.radius;
  21683. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21684. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21685. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21686. photometricScale = solidAngle;
  21687. break;
  21688. }
  21689. break;
  21690. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21691. // No fall off in hemisperic light.
  21692. photometricScale = 1.0;
  21693. break;
  21694. }
  21695. return photometricScale;
  21696. };
  21697. /**
  21698. * Reorder the light in the scene according to their defined priority.
  21699. * @hidden Internal Use Only
  21700. */
  21701. Light.prototype._reorderLightsInScene = function () {
  21702. var scene = this.getScene();
  21703. if (this._renderPriority != 0) {
  21704. scene.requireLightSorting = true;
  21705. }
  21706. this.getScene().sortLightsByPriority();
  21707. };
  21708. //lightmapMode Consts
  21709. /**
  21710. * If every light affecting the material is in this lightmapMode,
  21711. * material.lightmapTexture adds or multiplies
  21712. * (depends on material.useLightmapAsShadowmap)
  21713. * after every other light calculations.
  21714. */
  21715. Light.LIGHTMAP_DEFAULT = 0;
  21716. /**
  21717. * material.lightmapTexture as only diffuse lighting from this light
  21718. * adds only specular lighting from this light
  21719. * adds dynamic shadows
  21720. */
  21721. Light.LIGHTMAP_SPECULAR = 1;
  21722. /**
  21723. * material.lightmapTexture as only lighting
  21724. * no light calculation from this light
  21725. * only adds dynamic shadows from this light
  21726. */
  21727. Light.LIGHTMAP_SHADOWSONLY = 2;
  21728. // Intensity Mode Consts
  21729. /**
  21730. * Each light type uses the default quantity according to its type:
  21731. * point/spot lights use luminous intensity
  21732. * directional lights use illuminance
  21733. */
  21734. Light.INTENSITYMODE_AUTOMATIC = 0;
  21735. /**
  21736. * lumen (lm)
  21737. */
  21738. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  21739. /**
  21740. * candela (lm/sr)
  21741. */
  21742. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21743. /**
  21744. * lux (lm/m^2)
  21745. */
  21746. Light.INTENSITYMODE_ILLUMINANCE = 3;
  21747. /**
  21748. * nit (cd/m^2)
  21749. */
  21750. Light.INTENSITYMODE_LUMINANCE = 4;
  21751. // Light types ids const.
  21752. /**
  21753. * Light type const id of the point light.
  21754. */
  21755. Light.LIGHTTYPEID_POINTLIGHT = 0;
  21756. /**
  21757. * Light type const id of the directional light.
  21758. */
  21759. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21760. /**
  21761. * Light type const id of the spot light.
  21762. */
  21763. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  21764. /**
  21765. * Light type const id of the hemispheric light.
  21766. */
  21767. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21768. __decorate([
  21769. BABYLON.serializeAsColor3()
  21770. ], Light.prototype, "diffuse", void 0);
  21771. __decorate([
  21772. BABYLON.serializeAsColor3()
  21773. ], Light.prototype, "specular", void 0);
  21774. __decorate([
  21775. BABYLON.serialize()
  21776. ], Light.prototype, "intensity", void 0);
  21777. __decorate([
  21778. BABYLON.serialize()
  21779. ], Light.prototype, "range", void 0);
  21780. __decorate([
  21781. BABYLON.serialize()
  21782. ], Light.prototype, "intensityMode", null);
  21783. __decorate([
  21784. BABYLON.serialize()
  21785. ], Light.prototype, "radius", null);
  21786. __decorate([
  21787. BABYLON.serialize()
  21788. ], Light.prototype, "_renderPriority", void 0);
  21789. __decorate([
  21790. BABYLON.expandToProperty("_reorderLightsInScene")
  21791. ], Light.prototype, "renderPriority", void 0);
  21792. __decorate([
  21793. BABYLON.serialize("shadowEnabled")
  21794. ], Light.prototype, "_shadowEnabled", void 0);
  21795. __decorate([
  21796. BABYLON.serialize("excludeWithLayerMask")
  21797. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21798. __decorate([
  21799. BABYLON.serialize("includeOnlyWithLayerMask")
  21800. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21801. __decorate([
  21802. BABYLON.serialize("lightmapMode")
  21803. ], Light.prototype, "_lightmapMode", void 0);
  21804. return Light;
  21805. }(BABYLON.Node));
  21806. BABYLON.Light = Light;
  21807. })(BABYLON || (BABYLON = {}));
  21808. //# sourceMappingURL=babylon.light.js.map
  21809. var BABYLON;
  21810. (function (BABYLON) {
  21811. var Camera = /** @class */ (function (_super) {
  21812. __extends(Camera, _super);
  21813. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21814. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21815. var _this = _super.call(this, name, scene) || this;
  21816. /**
  21817. * The vector the camera should consider as up.
  21818. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21819. */
  21820. _this.upVector = BABYLON.Vector3.Up();
  21821. _this.orthoLeft = null;
  21822. _this.orthoRight = null;
  21823. _this.orthoBottom = null;
  21824. _this.orthoTop = null;
  21825. /**
  21826. * FOV is set in Radians. (default is 0.8)
  21827. */
  21828. _this.fov = 0.8;
  21829. _this.minZ = 1;
  21830. _this.maxZ = 10000.0;
  21831. _this.inertia = 0.9;
  21832. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21833. _this.isIntermediate = false;
  21834. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21835. /**
  21836. * Restricts the camera to viewing objects with the same layerMask.
  21837. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21838. */
  21839. _this.layerMask = 0x0FFFFFFF;
  21840. /**
  21841. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21842. */
  21843. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21844. // Camera rig members
  21845. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21846. _this._rigCameras = new Array();
  21847. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21848. _this._skipRendering = false;
  21849. _this.customRenderTargets = new Array();
  21850. // Observables
  21851. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21852. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21853. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21854. _this.onRestoreStateObservable = new BABYLON.Observable();
  21855. // Cache
  21856. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21857. _this._projectionMatrix = new BABYLON.Matrix();
  21858. _this._doNotComputeProjectionMatrix = false;
  21859. _this._worldMatrix = BABYLON.Matrix.Identity();
  21860. _this._postProcesses = new Array();
  21861. _this._transformMatrix = BABYLON.Matrix.Zero();
  21862. _this._activeMeshes = new BABYLON.SmartArray(256);
  21863. _this._globalPosition = BABYLON.Vector3.Zero();
  21864. _this._refreshFrustumPlanes = true;
  21865. _this.getScene().addCamera(_this);
  21866. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  21867. _this.getScene().activeCamera = _this;
  21868. }
  21869. _this.position = position;
  21870. return _this;
  21871. }
  21872. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21873. get: function () {
  21874. return Camera._PERSPECTIVE_CAMERA;
  21875. },
  21876. enumerable: true,
  21877. configurable: true
  21878. });
  21879. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21880. get: function () {
  21881. return Camera._ORTHOGRAPHIC_CAMERA;
  21882. },
  21883. enumerable: true,
  21884. configurable: true
  21885. });
  21886. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21887. /**
  21888. * This is the default FOV mode for perspective cameras.
  21889. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21890. *
  21891. */
  21892. get: function () {
  21893. return Camera._FOVMODE_VERTICAL_FIXED;
  21894. },
  21895. enumerable: true,
  21896. configurable: true
  21897. });
  21898. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21899. /**
  21900. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21901. *
  21902. */
  21903. get: function () {
  21904. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21905. },
  21906. enumerable: true,
  21907. configurable: true
  21908. });
  21909. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21910. get: function () {
  21911. return Camera._RIG_MODE_NONE;
  21912. },
  21913. enumerable: true,
  21914. configurable: true
  21915. });
  21916. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21917. get: function () {
  21918. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21919. },
  21920. enumerable: true,
  21921. configurable: true
  21922. });
  21923. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21924. get: function () {
  21925. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21926. },
  21927. enumerable: true,
  21928. configurable: true
  21929. });
  21930. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21931. get: function () {
  21932. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21933. },
  21934. enumerable: true,
  21935. configurable: true
  21936. });
  21937. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21938. get: function () {
  21939. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21940. },
  21941. enumerable: true,
  21942. configurable: true
  21943. });
  21944. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21945. get: function () {
  21946. return Camera._RIG_MODE_VR;
  21947. },
  21948. enumerable: true,
  21949. configurable: true
  21950. });
  21951. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21952. get: function () {
  21953. return Camera._RIG_MODE_WEBVR;
  21954. },
  21955. enumerable: true,
  21956. configurable: true
  21957. });
  21958. /**
  21959. * Store current camera state (fov, position, etc..)
  21960. */
  21961. Camera.prototype.storeState = function () {
  21962. this._stateStored = true;
  21963. this._storedFov = this.fov;
  21964. return this;
  21965. };
  21966. /**
  21967. * Restores the camera state values if it has been stored. You must call storeState() first
  21968. */
  21969. Camera.prototype._restoreStateValues = function () {
  21970. if (!this._stateStored) {
  21971. return false;
  21972. }
  21973. this.fov = this._storedFov;
  21974. return true;
  21975. };
  21976. /**
  21977. * Restored camera state. You must call storeState() first
  21978. */
  21979. Camera.prototype.restoreState = function () {
  21980. if (this._restoreStateValues()) {
  21981. this.onRestoreStateObservable.notifyObservers(this);
  21982. return true;
  21983. }
  21984. return false;
  21985. };
  21986. Camera.prototype.getClassName = function () {
  21987. return "Camera";
  21988. };
  21989. /**
  21990. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21991. */
  21992. Camera.prototype.toString = function (fullDetails) {
  21993. var ret = "Name: " + this.name;
  21994. ret += ", type: " + this.getClassName();
  21995. if (this.animations) {
  21996. for (var i = 0; i < this.animations.length; i++) {
  21997. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21998. }
  21999. }
  22000. if (fullDetails) {
  22001. }
  22002. return ret;
  22003. };
  22004. Object.defineProperty(Camera.prototype, "globalPosition", {
  22005. get: function () {
  22006. return this._globalPosition;
  22007. },
  22008. enumerable: true,
  22009. configurable: true
  22010. });
  22011. Camera.prototype.getActiveMeshes = function () {
  22012. return this._activeMeshes;
  22013. };
  22014. Camera.prototype.isActiveMesh = function (mesh) {
  22015. return (this._activeMeshes.indexOf(mesh) !== -1);
  22016. };
  22017. /**
  22018. * Is this camera ready to be used/rendered
  22019. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22020. * @return true if the camera is ready
  22021. */
  22022. Camera.prototype.isReady = function (completeCheck) {
  22023. if (completeCheck === void 0) { completeCheck = false; }
  22024. if (completeCheck) {
  22025. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22026. var pp = _a[_i];
  22027. if (pp && !pp.isReady()) {
  22028. return false;
  22029. }
  22030. }
  22031. }
  22032. return _super.prototype.isReady.call(this, completeCheck);
  22033. };
  22034. //Cache
  22035. Camera.prototype._initCache = function () {
  22036. _super.prototype._initCache.call(this);
  22037. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22038. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22039. this._cache.mode = undefined;
  22040. this._cache.minZ = undefined;
  22041. this._cache.maxZ = undefined;
  22042. this._cache.fov = undefined;
  22043. this._cache.fovMode = undefined;
  22044. this._cache.aspectRatio = undefined;
  22045. this._cache.orthoLeft = undefined;
  22046. this._cache.orthoRight = undefined;
  22047. this._cache.orthoBottom = undefined;
  22048. this._cache.orthoTop = undefined;
  22049. this._cache.renderWidth = undefined;
  22050. this._cache.renderHeight = undefined;
  22051. };
  22052. Camera.prototype._updateCache = function (ignoreParentClass) {
  22053. if (!ignoreParentClass) {
  22054. _super.prototype._updateCache.call(this);
  22055. }
  22056. this._cache.position.copyFrom(this.position);
  22057. this._cache.upVector.copyFrom(this.upVector);
  22058. };
  22059. // Synchronized
  22060. Camera.prototype._isSynchronized = function () {
  22061. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22062. };
  22063. Camera.prototype._isSynchronizedViewMatrix = function () {
  22064. if (!_super.prototype._isSynchronized.call(this))
  22065. return false;
  22066. return this._cache.position.equals(this.position)
  22067. && this._cache.upVector.equals(this.upVector)
  22068. && this.isSynchronizedWithParent();
  22069. };
  22070. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22071. var check = this._cache.mode === this.mode
  22072. && this._cache.minZ === this.minZ
  22073. && this._cache.maxZ === this.maxZ;
  22074. if (!check) {
  22075. return false;
  22076. }
  22077. var engine = this.getEngine();
  22078. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22079. check = this._cache.fov === this.fov
  22080. && this._cache.fovMode === this.fovMode
  22081. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22082. }
  22083. else {
  22084. check = this._cache.orthoLeft === this.orthoLeft
  22085. && this._cache.orthoRight === this.orthoRight
  22086. && this._cache.orthoBottom === this.orthoBottom
  22087. && this._cache.orthoTop === this.orthoTop
  22088. && this._cache.renderWidth === engine.getRenderWidth()
  22089. && this._cache.renderHeight === engine.getRenderHeight();
  22090. }
  22091. return check;
  22092. };
  22093. // Controls
  22094. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22095. };
  22096. Camera.prototype.detachControl = function (element) {
  22097. };
  22098. Camera.prototype.update = function () {
  22099. this._checkInputs();
  22100. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22101. this._updateRigCameras();
  22102. }
  22103. };
  22104. Camera.prototype._checkInputs = function () {
  22105. this.onAfterCheckInputsObservable.notifyObservers(this);
  22106. };
  22107. Object.defineProperty(Camera.prototype, "rigCameras", {
  22108. get: function () {
  22109. return this._rigCameras;
  22110. },
  22111. enumerable: true,
  22112. configurable: true
  22113. });
  22114. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22115. get: function () {
  22116. return this._rigPostProcess;
  22117. },
  22118. enumerable: true,
  22119. configurable: true
  22120. });
  22121. /**
  22122. * Internal, gets the first post proces.
  22123. * @returns the first post process to be run on this camera.
  22124. */
  22125. Camera.prototype._getFirstPostProcess = function () {
  22126. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22127. if (this._postProcesses[ppIndex] !== null) {
  22128. return this._postProcesses[ppIndex];
  22129. }
  22130. }
  22131. return null;
  22132. };
  22133. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22134. // invalidate framebuffer
  22135. var firstPostProcess = this._getFirstPostProcess();
  22136. if (firstPostProcess) {
  22137. firstPostProcess.markTextureDirty();
  22138. }
  22139. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22140. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22141. var cam = this._rigCameras[i];
  22142. var rigPostProcess = cam._rigPostProcess;
  22143. // for VR rig, there does not have to be a post process
  22144. if (rigPostProcess) {
  22145. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22146. if (isPass) {
  22147. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22148. cam.isIntermediate = this._postProcesses.length === 0;
  22149. }
  22150. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22151. rigPostProcess.markTextureDirty();
  22152. }
  22153. else {
  22154. cam._postProcesses = this._postProcesses.slice(0);
  22155. }
  22156. }
  22157. };
  22158. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22159. if (insertAt === void 0) { insertAt = null; }
  22160. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22161. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22162. return 0;
  22163. }
  22164. if (insertAt == null || insertAt < 0) {
  22165. this._postProcesses.push(postProcess);
  22166. }
  22167. else if (this._postProcesses[insertAt] === null) {
  22168. this._postProcesses[insertAt] = postProcess;
  22169. }
  22170. else {
  22171. this._postProcesses.splice(insertAt, 0, postProcess);
  22172. }
  22173. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22174. return this._postProcesses.indexOf(postProcess);
  22175. };
  22176. Camera.prototype.detachPostProcess = function (postProcess) {
  22177. var idx = this._postProcesses.indexOf(postProcess);
  22178. if (idx !== -1) {
  22179. this._postProcesses[idx] = null;
  22180. }
  22181. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22182. };
  22183. Camera.prototype.getWorldMatrix = function () {
  22184. if (this._isSynchronizedViewMatrix()) {
  22185. return this._worldMatrix;
  22186. }
  22187. // Getting the the view matrix will also compute the world matrix.
  22188. this.getViewMatrix();
  22189. return this._worldMatrix;
  22190. };
  22191. Camera.prototype._getViewMatrix = function () {
  22192. return BABYLON.Matrix.Identity();
  22193. };
  22194. Camera.prototype.getViewMatrix = function (force) {
  22195. if (!force && this._isSynchronizedViewMatrix()) {
  22196. return this._computedViewMatrix;
  22197. }
  22198. this.updateCache();
  22199. this._computedViewMatrix = this._getViewMatrix();
  22200. this._currentRenderId = this.getScene().getRenderId();
  22201. this._childRenderId = this._currentRenderId;
  22202. this._refreshFrustumPlanes = true;
  22203. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22204. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22205. }
  22206. this.onViewMatrixChangedObservable.notifyObservers(this);
  22207. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22208. return this._computedViewMatrix;
  22209. };
  22210. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22211. this._doNotComputeProjectionMatrix = true;
  22212. if (projection !== undefined) {
  22213. this._projectionMatrix = projection;
  22214. }
  22215. };
  22216. ;
  22217. Camera.prototype.unfreezeProjectionMatrix = function () {
  22218. this._doNotComputeProjectionMatrix = false;
  22219. };
  22220. ;
  22221. Camera.prototype.getProjectionMatrix = function (force) {
  22222. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22223. return this._projectionMatrix;
  22224. }
  22225. // Cache
  22226. this._cache.mode = this.mode;
  22227. this._cache.minZ = this.minZ;
  22228. this._cache.maxZ = this.maxZ;
  22229. // Matrix
  22230. this._refreshFrustumPlanes = true;
  22231. var engine = this.getEngine();
  22232. var scene = this.getScene();
  22233. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22234. this._cache.fov = this.fov;
  22235. this._cache.fovMode = this.fovMode;
  22236. this._cache.aspectRatio = engine.getAspectRatio(this);
  22237. if (this.minZ <= 0) {
  22238. this.minZ = 0.1;
  22239. }
  22240. if (scene.useRightHandedSystem) {
  22241. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22242. }
  22243. else {
  22244. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22245. }
  22246. }
  22247. else {
  22248. var halfWidth = engine.getRenderWidth() / 2.0;
  22249. var halfHeight = engine.getRenderHeight() / 2.0;
  22250. if (scene.useRightHandedSystem) {
  22251. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22252. }
  22253. else {
  22254. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22255. }
  22256. this._cache.orthoLeft = this.orthoLeft;
  22257. this._cache.orthoRight = this.orthoRight;
  22258. this._cache.orthoBottom = this.orthoBottom;
  22259. this._cache.orthoTop = this.orthoTop;
  22260. this._cache.renderWidth = engine.getRenderWidth();
  22261. this._cache.renderHeight = engine.getRenderHeight();
  22262. }
  22263. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22264. return this._projectionMatrix;
  22265. };
  22266. Camera.prototype.getTranformationMatrix = function () {
  22267. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22268. return this._transformMatrix;
  22269. };
  22270. Camera.prototype.updateFrustumPlanes = function () {
  22271. if (!this._refreshFrustumPlanes) {
  22272. return;
  22273. }
  22274. this.getTranformationMatrix();
  22275. if (!this._frustumPlanes) {
  22276. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22277. }
  22278. else {
  22279. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22280. }
  22281. this._refreshFrustumPlanes = false;
  22282. };
  22283. Camera.prototype.isInFrustum = function (target) {
  22284. this.updateFrustumPlanes();
  22285. return target.isInFrustum(this._frustumPlanes);
  22286. };
  22287. Camera.prototype.isCompletelyInFrustum = function (target) {
  22288. this.updateFrustumPlanes();
  22289. return target.isCompletelyInFrustum(this._frustumPlanes);
  22290. };
  22291. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22292. if (length === void 0) { length = 100; }
  22293. if (!transform) {
  22294. transform = this.getWorldMatrix();
  22295. }
  22296. if (!origin) {
  22297. origin = this.position;
  22298. }
  22299. var forward = new BABYLON.Vector3(0, 0, 1);
  22300. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22301. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22302. return new BABYLON.Ray(origin, direction, length);
  22303. };
  22304. /**
  22305. * Releases resources associated with this node.
  22306. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22307. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22308. */
  22309. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22310. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22311. // Observables
  22312. this.onViewMatrixChangedObservable.clear();
  22313. this.onProjectionMatrixChangedObservable.clear();
  22314. this.onAfterCheckInputsObservable.clear();
  22315. this.onRestoreStateObservable.clear();
  22316. // Inputs
  22317. if (this.inputs) {
  22318. this.inputs.clear();
  22319. }
  22320. // Animations
  22321. this.getScene().stopAnimation(this);
  22322. // Remove from scene
  22323. this.getScene().removeCamera(this);
  22324. while (this._rigCameras.length > 0) {
  22325. var camera = this._rigCameras.pop();
  22326. if (camera) {
  22327. camera.dispose();
  22328. }
  22329. }
  22330. // Postprocesses
  22331. if (this._rigPostProcess) {
  22332. this._rigPostProcess.dispose(this);
  22333. this._rigPostProcess = null;
  22334. this._postProcesses = [];
  22335. }
  22336. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22337. this._rigPostProcess = null;
  22338. this._postProcesses = [];
  22339. }
  22340. else {
  22341. var i = this._postProcesses.length;
  22342. while (--i >= 0) {
  22343. var postProcess = this._postProcesses[i];
  22344. if (postProcess) {
  22345. postProcess.dispose(this);
  22346. }
  22347. }
  22348. }
  22349. // Render targets
  22350. var i = this.customRenderTargets.length;
  22351. while (--i >= 0) {
  22352. this.customRenderTargets[i].dispose();
  22353. }
  22354. this.customRenderTargets = [];
  22355. // Active Meshes
  22356. this._activeMeshes.dispose();
  22357. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22358. };
  22359. Object.defineProperty(Camera.prototype, "leftCamera", {
  22360. // ---- Camera rigs section ----
  22361. get: function () {
  22362. if (this._rigCameras.length < 1) {
  22363. return null;
  22364. }
  22365. return this._rigCameras[0];
  22366. },
  22367. enumerable: true,
  22368. configurable: true
  22369. });
  22370. Object.defineProperty(Camera.prototype, "rightCamera", {
  22371. get: function () {
  22372. if (this._rigCameras.length < 2) {
  22373. return null;
  22374. }
  22375. return this._rigCameras[1];
  22376. },
  22377. enumerable: true,
  22378. configurable: true
  22379. });
  22380. Camera.prototype.getLeftTarget = function () {
  22381. if (this._rigCameras.length < 1) {
  22382. return null;
  22383. }
  22384. return this._rigCameras[0].getTarget();
  22385. };
  22386. Camera.prototype.getRightTarget = function () {
  22387. if (this._rigCameras.length < 2) {
  22388. return null;
  22389. }
  22390. return this._rigCameras[1].getTarget();
  22391. };
  22392. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22393. if (this.cameraRigMode === mode) {
  22394. return;
  22395. }
  22396. while (this._rigCameras.length > 0) {
  22397. var camera = this._rigCameras.pop();
  22398. if (camera) {
  22399. camera.dispose();
  22400. }
  22401. }
  22402. this.cameraRigMode = mode;
  22403. this._cameraRigParams = {};
  22404. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22405. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22406. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22407. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22408. // create the rig cameras, unless none
  22409. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22410. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22411. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22412. if (leftCamera && rightCamera) {
  22413. this._rigCameras.push(leftCamera);
  22414. this._rigCameras.push(rightCamera);
  22415. }
  22416. }
  22417. switch (this.cameraRigMode) {
  22418. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22419. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22420. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22421. break;
  22422. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22423. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22424. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22425. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22426. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22427. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22428. break;
  22429. case Camera.RIG_MODE_VR:
  22430. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22431. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22432. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22433. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22434. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22435. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22436. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22437. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22438. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22439. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22440. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22441. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22442. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22443. if (metrics.compensateDistortion) {
  22444. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22445. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22446. }
  22447. break;
  22448. case Camera.RIG_MODE_WEBVR:
  22449. if (rigParams.vrDisplay) {
  22450. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22451. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22452. //Left eye
  22453. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22454. this._rigCameras[0].setCameraRigParameter("left", true);
  22455. //leaving this for future reference
  22456. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22457. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22458. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22459. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22460. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22461. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22462. this._rigCameras[0].parent = this;
  22463. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22464. //Right eye
  22465. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22466. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22467. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22468. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22469. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22470. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22471. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22472. this._rigCameras[1].parent = this;
  22473. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22474. if (Camera.UseAlternateWebVRRendering) {
  22475. this._rigCameras[1]._skipRendering = true;
  22476. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22477. }
  22478. }
  22479. break;
  22480. }
  22481. this._cascadePostProcessesToRigCams();
  22482. this.update();
  22483. };
  22484. Camera.prototype._getVRProjectionMatrix = function () {
  22485. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22486. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22487. return this._projectionMatrix;
  22488. };
  22489. Camera.prototype._updateCameraRotationMatrix = function () {
  22490. //Here for WebVR
  22491. };
  22492. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22493. //Here for WebVR
  22494. };
  22495. /**
  22496. * This function MUST be overwritten by the different WebVR cameras available.
  22497. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22498. */
  22499. Camera.prototype._getWebVRProjectionMatrix = function () {
  22500. return BABYLON.Matrix.Identity();
  22501. };
  22502. /**
  22503. * This function MUST be overwritten by the different WebVR cameras available.
  22504. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22505. */
  22506. Camera.prototype._getWebVRViewMatrix = function () {
  22507. return BABYLON.Matrix.Identity();
  22508. };
  22509. Camera.prototype.setCameraRigParameter = function (name, value) {
  22510. if (!this._cameraRigParams) {
  22511. this._cameraRigParams = {};
  22512. }
  22513. this._cameraRigParams[name] = value;
  22514. //provisionnally:
  22515. if (name === "interaxialDistance") {
  22516. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22517. }
  22518. };
  22519. /**
  22520. * needs to be overridden by children so sub has required properties to be copied
  22521. */
  22522. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22523. return null;
  22524. };
  22525. /**
  22526. * May need to be overridden by children
  22527. */
  22528. Camera.prototype._updateRigCameras = function () {
  22529. for (var i = 0; i < this._rigCameras.length; i++) {
  22530. this._rigCameras[i].minZ = this.minZ;
  22531. this._rigCameras[i].maxZ = this.maxZ;
  22532. this._rigCameras[i].fov = this.fov;
  22533. }
  22534. // only update viewport when ANAGLYPH
  22535. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22536. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22537. }
  22538. };
  22539. Camera.prototype._setupInputs = function () {
  22540. };
  22541. Camera.prototype.serialize = function () {
  22542. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22543. // Type
  22544. serializationObject.type = this.getClassName();
  22545. // Parent
  22546. if (this.parent) {
  22547. serializationObject.parentId = this.parent.id;
  22548. }
  22549. if (this.inputs) {
  22550. this.inputs.serialize(serializationObject);
  22551. }
  22552. // Animations
  22553. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22554. serializationObject.ranges = this.serializeAnimationRanges();
  22555. return serializationObject;
  22556. };
  22557. Camera.prototype.clone = function (name) {
  22558. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22559. };
  22560. Camera.prototype.getDirection = function (localAxis) {
  22561. var result = BABYLON.Vector3.Zero();
  22562. this.getDirectionToRef(localAxis, result);
  22563. return result;
  22564. };
  22565. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22566. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22567. };
  22568. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22569. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22570. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22571. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22572. interaxial_distance: interaxial_distance,
  22573. isStereoscopicSideBySide: isStereoscopicSideBySide
  22574. });
  22575. if (constructorFunc) {
  22576. return constructorFunc;
  22577. }
  22578. // Default to universal camera
  22579. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22580. };
  22581. Camera.prototype.computeWorldMatrix = function () {
  22582. return this.getWorldMatrix();
  22583. };
  22584. Camera.Parse = function (parsedCamera, scene) {
  22585. var type = parsedCamera.type;
  22586. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22587. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22588. // Parent
  22589. if (parsedCamera.parentId) {
  22590. camera._waitingParentId = parsedCamera.parentId;
  22591. }
  22592. //If camera has an input manager, let it parse inputs settings
  22593. if (camera.inputs) {
  22594. camera.inputs.parse(parsedCamera);
  22595. camera._setupInputs();
  22596. }
  22597. if (camera.setPosition) { // need to force position
  22598. camera.position.copyFromFloats(0, 0, 0);
  22599. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22600. }
  22601. // Target
  22602. if (parsedCamera.target) {
  22603. if (camera.setTarget) {
  22604. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22605. }
  22606. }
  22607. // Apply 3d rig, when found
  22608. if (parsedCamera.cameraRigMode) {
  22609. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22610. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22611. }
  22612. // Animations
  22613. if (parsedCamera.animations) {
  22614. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22615. var parsedAnimation = parsedCamera.animations[animationIndex];
  22616. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22617. }
  22618. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22619. }
  22620. if (parsedCamera.autoAnimate) {
  22621. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22622. }
  22623. return camera;
  22624. };
  22625. // Statics
  22626. Camera._PERSPECTIVE_CAMERA = 0;
  22627. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22628. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22629. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22630. Camera._RIG_MODE_NONE = 0;
  22631. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22632. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22633. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22634. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22635. Camera._RIG_MODE_VR = 20;
  22636. Camera._RIG_MODE_WEBVR = 21;
  22637. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22638. Camera.UseAlternateWebVRRendering = false;
  22639. __decorate([
  22640. BABYLON.serializeAsVector3()
  22641. ], Camera.prototype, "position", void 0);
  22642. __decorate([
  22643. BABYLON.serializeAsVector3()
  22644. ], Camera.prototype, "upVector", void 0);
  22645. __decorate([
  22646. BABYLON.serialize()
  22647. ], Camera.prototype, "orthoLeft", void 0);
  22648. __decorate([
  22649. BABYLON.serialize()
  22650. ], Camera.prototype, "orthoRight", void 0);
  22651. __decorate([
  22652. BABYLON.serialize()
  22653. ], Camera.prototype, "orthoBottom", void 0);
  22654. __decorate([
  22655. BABYLON.serialize()
  22656. ], Camera.prototype, "orthoTop", void 0);
  22657. __decorate([
  22658. BABYLON.serialize()
  22659. ], Camera.prototype, "fov", void 0);
  22660. __decorate([
  22661. BABYLON.serialize()
  22662. ], Camera.prototype, "minZ", void 0);
  22663. __decorate([
  22664. BABYLON.serialize()
  22665. ], Camera.prototype, "maxZ", void 0);
  22666. __decorate([
  22667. BABYLON.serialize()
  22668. ], Camera.prototype, "inertia", void 0);
  22669. __decorate([
  22670. BABYLON.serialize()
  22671. ], Camera.prototype, "mode", void 0);
  22672. __decorate([
  22673. BABYLON.serialize()
  22674. ], Camera.prototype, "layerMask", void 0);
  22675. __decorate([
  22676. BABYLON.serialize()
  22677. ], Camera.prototype, "fovMode", void 0);
  22678. __decorate([
  22679. BABYLON.serialize()
  22680. ], Camera.prototype, "cameraRigMode", void 0);
  22681. __decorate([
  22682. BABYLON.serialize()
  22683. ], Camera.prototype, "interaxialDistance", void 0);
  22684. __decorate([
  22685. BABYLON.serialize()
  22686. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22687. return Camera;
  22688. }(BABYLON.Node));
  22689. BABYLON.Camera = Camera;
  22690. })(BABYLON || (BABYLON = {}));
  22691. //# sourceMappingURL=babylon.camera.js.map
  22692. var BABYLON;
  22693. (function (BABYLON) {
  22694. var RenderingManager = /** @class */ (function () {
  22695. function RenderingManager(scene) {
  22696. /**
  22697. * Hidden
  22698. */
  22699. this._useSceneAutoClearSetup = false;
  22700. this._renderingGroups = new Array();
  22701. this._autoClearDepthStencil = {};
  22702. this._customOpaqueSortCompareFn = {};
  22703. this._customAlphaTestSortCompareFn = {};
  22704. this._customTransparentSortCompareFn = {};
  22705. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  22706. this._scene = scene;
  22707. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22708. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22709. }
  22710. }
  22711. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22712. if (depth === void 0) { depth = true; }
  22713. if (stencil === void 0) { stencil = true; }
  22714. if (this._depthStencilBufferAlreadyCleaned) {
  22715. return;
  22716. }
  22717. this._scene.getEngine().clear(null, false, depth, stencil);
  22718. this._depthStencilBufferAlreadyCleaned = true;
  22719. };
  22720. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22721. // Update the observable context (not null as it only goes away on dispose)
  22722. var info = this._renderingGroupInfo;
  22723. info.scene = this._scene;
  22724. info.camera = this._scene.activeCamera;
  22725. // Dispatch sprites
  22726. if (renderSprites) {
  22727. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22728. var manager = this._scene.spriteManagers[index];
  22729. this.dispatchSprites(manager);
  22730. }
  22731. }
  22732. // Render
  22733. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22734. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22735. var renderingGroup = this._renderingGroups[index];
  22736. if (!renderingGroup)
  22737. continue;
  22738. var renderingGroupMask = Math.pow(2, index);
  22739. info.renderingGroupId = index;
  22740. // Before Observable
  22741. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22742. // Clear depth/stencil if needed
  22743. if (RenderingManager.AUTOCLEAR) {
  22744. var autoClear = this._useSceneAutoClearSetup ?
  22745. this._scene.getAutoClearDepthStencilSetup(index) :
  22746. this._autoClearDepthStencil[index];
  22747. if (autoClear && autoClear.autoClear) {
  22748. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22749. }
  22750. }
  22751. // Render
  22752. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  22753. var step = _a[_i];
  22754. step.action(index);
  22755. }
  22756. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22757. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  22758. var step = _c[_b];
  22759. step.action(index);
  22760. }
  22761. // After Observable
  22762. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22763. }
  22764. };
  22765. RenderingManager.prototype.reset = function () {
  22766. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22767. var renderingGroup = this._renderingGroups[index];
  22768. if (renderingGroup) {
  22769. renderingGroup.prepare();
  22770. }
  22771. }
  22772. };
  22773. RenderingManager.prototype.dispose = function () {
  22774. this.freeRenderingGroups();
  22775. this._renderingGroups.length = 0;
  22776. this._renderingGroupInfo = null;
  22777. };
  22778. /**
  22779. * Clear the info related to rendering groups preventing retention points during dispose.
  22780. */
  22781. RenderingManager.prototype.freeRenderingGroups = function () {
  22782. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22783. var renderingGroup = this._renderingGroups[index];
  22784. if (renderingGroup) {
  22785. renderingGroup.dispose();
  22786. }
  22787. }
  22788. };
  22789. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22790. if (this._renderingGroups[renderingGroupId] === undefined) {
  22791. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22792. }
  22793. };
  22794. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22795. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22796. this._prepareRenderingGroup(renderingGroupId);
  22797. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22798. };
  22799. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22800. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22801. this._prepareRenderingGroup(renderingGroupId);
  22802. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22803. };
  22804. /**
  22805. * @param subMesh The submesh to dispatch
  22806. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22807. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22808. */
  22809. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22810. if (mesh === undefined) {
  22811. mesh = subMesh.getMesh();
  22812. }
  22813. var renderingGroupId = mesh.renderingGroupId || 0;
  22814. this._prepareRenderingGroup(renderingGroupId);
  22815. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22816. };
  22817. /**
  22818. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22819. * This allowed control for front to back rendering or reversly depending of the special needs.
  22820. *
  22821. * @param renderingGroupId The rendering group id corresponding to its index
  22822. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22823. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22824. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22825. */
  22826. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22827. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22828. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22829. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22830. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22831. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22832. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22833. if (this._renderingGroups[renderingGroupId]) {
  22834. var group = this._renderingGroups[renderingGroupId];
  22835. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22836. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22837. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22838. }
  22839. };
  22840. /**
  22841. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22842. *
  22843. * @param renderingGroupId The rendering group id corresponding to its index
  22844. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22845. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22846. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22847. */
  22848. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22849. if (depth === void 0) { depth = true; }
  22850. if (stencil === void 0) { stencil = true; }
  22851. this._autoClearDepthStencil[renderingGroupId] = {
  22852. autoClear: autoClearDepthStencil,
  22853. depth: depth,
  22854. stencil: stencil
  22855. };
  22856. };
  22857. /**
  22858. * Gets the current auto clear configuration for one rendering group of the rendering
  22859. * manager.
  22860. * @param index the rendering group index to get the information for
  22861. * @returns The auto clear setup for the requested rendering group
  22862. */
  22863. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  22864. return this._autoClearDepthStencil[index];
  22865. };
  22866. /**
  22867. * The max id used for rendering groups (not included)
  22868. */
  22869. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22870. /**
  22871. * The min id used for rendering groups (included)
  22872. */
  22873. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22874. /**
  22875. * Used to globally prevent autoclearing scenes.
  22876. */
  22877. RenderingManager.AUTOCLEAR = true;
  22878. return RenderingManager;
  22879. }());
  22880. BABYLON.RenderingManager = RenderingManager;
  22881. })(BABYLON || (BABYLON = {}));
  22882. //# sourceMappingURL=babylon.renderingManager.js.map
  22883. var BABYLON;
  22884. (function (BABYLON) {
  22885. var RenderingGroup = /** @class */ (function () {
  22886. /**
  22887. * Creates a new rendering group.
  22888. * @param index The rendering group index
  22889. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22890. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22891. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22892. */
  22893. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22894. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22895. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22896. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22897. this.index = index;
  22898. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22899. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22900. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22901. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22902. this._particleSystems = new BABYLON.SmartArray(256);
  22903. this._spriteManagers = new BABYLON.SmartArray(256);
  22904. this._edgesRenderers = new BABYLON.SmartArray(16);
  22905. this._scene = scene;
  22906. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22907. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22908. this.transparentSortCompareFn = transparentSortCompareFn;
  22909. }
  22910. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22911. /**
  22912. * Set the opaque sort comparison function.
  22913. * If null the sub meshes will be render in the order they were created
  22914. */
  22915. set: function (value) {
  22916. this._opaqueSortCompareFn = value;
  22917. if (value) {
  22918. this._renderOpaque = this.renderOpaqueSorted;
  22919. }
  22920. else {
  22921. this._renderOpaque = RenderingGroup.renderUnsorted;
  22922. }
  22923. },
  22924. enumerable: true,
  22925. configurable: true
  22926. });
  22927. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22928. /**
  22929. * Set the alpha test sort comparison function.
  22930. * If null the sub meshes will be render in the order they were created
  22931. */
  22932. set: function (value) {
  22933. this._alphaTestSortCompareFn = value;
  22934. if (value) {
  22935. this._renderAlphaTest = this.renderAlphaTestSorted;
  22936. }
  22937. else {
  22938. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22939. }
  22940. },
  22941. enumerable: true,
  22942. configurable: true
  22943. });
  22944. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22945. /**
  22946. * Set the transparent sort comparison function.
  22947. * If null the sub meshes will be render in the order they were created
  22948. */
  22949. set: function (value) {
  22950. if (value) {
  22951. this._transparentSortCompareFn = value;
  22952. }
  22953. else {
  22954. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22955. }
  22956. this._renderTransparent = this.renderTransparentSorted;
  22957. },
  22958. enumerable: true,
  22959. configurable: true
  22960. });
  22961. /**
  22962. * Render all the sub meshes contained in the group.
  22963. * @param customRenderFunction Used to override the default render behaviour of the group.
  22964. * @returns true if rendered some submeshes.
  22965. */
  22966. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22967. if (customRenderFunction) {
  22968. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22969. return;
  22970. }
  22971. var engine = this._scene.getEngine();
  22972. // Depth only
  22973. if (this._depthOnlySubMeshes.length !== 0) {
  22974. engine.setColorWrite(false);
  22975. this._renderAlphaTest(this._depthOnlySubMeshes);
  22976. engine.setColorWrite(true);
  22977. }
  22978. // Opaque
  22979. if (this._opaqueSubMeshes.length !== 0) {
  22980. this._renderOpaque(this._opaqueSubMeshes);
  22981. }
  22982. // Alpha test
  22983. if (this._alphaTestSubMeshes.length !== 0) {
  22984. this._renderAlphaTest(this._alphaTestSubMeshes);
  22985. }
  22986. var stencilState = engine.getStencilBuffer();
  22987. engine.setStencilBuffer(false);
  22988. // Sprites
  22989. if (renderSprites) {
  22990. this._renderSprites();
  22991. }
  22992. // Particles
  22993. if (renderParticles) {
  22994. this._renderParticles(activeMeshes);
  22995. }
  22996. if (this.onBeforeTransparentRendering) {
  22997. this.onBeforeTransparentRendering();
  22998. }
  22999. // Transparent
  23000. if (this._transparentSubMeshes.length !== 0) {
  23001. this._renderTransparent(this._transparentSubMeshes);
  23002. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23003. }
  23004. // Set back stencil to false in case it changes before the edge renderer.
  23005. engine.setStencilBuffer(false);
  23006. // Edges
  23007. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23008. this._edgesRenderers.data[edgesRendererIndex].render();
  23009. }
  23010. // Restore Stencil state.
  23011. engine.setStencilBuffer(stencilState);
  23012. };
  23013. /**
  23014. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23015. * @param subMeshes The submeshes to render
  23016. */
  23017. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23018. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23019. };
  23020. /**
  23021. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23022. * @param subMeshes The submeshes to render
  23023. */
  23024. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23025. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23026. };
  23027. /**
  23028. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23029. * @param subMeshes The submeshes to render
  23030. */
  23031. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23032. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23033. };
  23034. /**
  23035. * Renders the submeshes in a specified order.
  23036. * @param subMeshes The submeshes to sort before render
  23037. * @param sortCompareFn The comparison function use to sort
  23038. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23039. * @param transparent Specifies to activate blending if true
  23040. */
  23041. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23042. var subIndex = 0;
  23043. var subMesh;
  23044. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23045. for (; subIndex < subMeshes.length; subIndex++) {
  23046. subMesh = subMeshes.data[subIndex];
  23047. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23048. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23049. }
  23050. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23051. if (sortCompareFn) {
  23052. sortedArray.sort(sortCompareFn);
  23053. }
  23054. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23055. subMesh = sortedArray[subIndex];
  23056. if (transparent) {
  23057. var material = subMesh.getMaterial();
  23058. if (material && material.needDepthPrePass) {
  23059. var engine = material.getScene().getEngine();
  23060. engine.setColorWrite(false);
  23061. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23062. subMesh.render(false);
  23063. engine.setColorWrite(true);
  23064. }
  23065. }
  23066. subMesh.render(transparent);
  23067. }
  23068. };
  23069. /**
  23070. * Renders the submeshes in the order they were dispatched (no sort applied).
  23071. * @param subMeshes The submeshes to render
  23072. */
  23073. RenderingGroup.renderUnsorted = function (subMeshes) {
  23074. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23075. var submesh = subMeshes.data[subIndex];
  23076. submesh.render(false);
  23077. }
  23078. };
  23079. /**
  23080. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23081. * are rendered back to front if in the same alpha index.
  23082. *
  23083. * @param a The first submesh
  23084. * @param b The second submesh
  23085. * @returns The result of the comparison
  23086. */
  23087. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23088. // Alpha index first
  23089. if (a._alphaIndex > b._alphaIndex) {
  23090. return 1;
  23091. }
  23092. if (a._alphaIndex < b._alphaIndex) {
  23093. return -1;
  23094. }
  23095. // Then distance to camera
  23096. return RenderingGroup.backToFrontSortCompare(a, b);
  23097. };
  23098. /**
  23099. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23100. * are rendered back to front.
  23101. *
  23102. * @param a The first submesh
  23103. * @param b The second submesh
  23104. * @returns The result of the comparison
  23105. */
  23106. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23107. // Then distance to camera
  23108. if (a._distanceToCamera < b._distanceToCamera) {
  23109. return 1;
  23110. }
  23111. if (a._distanceToCamera > b._distanceToCamera) {
  23112. return -1;
  23113. }
  23114. return 0;
  23115. };
  23116. /**
  23117. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23118. * are rendered front to back (prevent overdraw).
  23119. *
  23120. * @param a The first submesh
  23121. * @param b The second submesh
  23122. * @returns The result of the comparison
  23123. */
  23124. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23125. // Then distance to camera
  23126. if (a._distanceToCamera < b._distanceToCamera) {
  23127. return -1;
  23128. }
  23129. if (a._distanceToCamera > b._distanceToCamera) {
  23130. return 1;
  23131. }
  23132. return 0;
  23133. };
  23134. /**
  23135. * Resets the different lists of submeshes to prepare a new frame.
  23136. */
  23137. RenderingGroup.prototype.prepare = function () {
  23138. this._opaqueSubMeshes.reset();
  23139. this._transparentSubMeshes.reset();
  23140. this._alphaTestSubMeshes.reset();
  23141. this._depthOnlySubMeshes.reset();
  23142. this._particleSystems.reset();
  23143. this._spriteManagers.reset();
  23144. this._edgesRenderers.reset();
  23145. };
  23146. RenderingGroup.prototype.dispose = function () {
  23147. this._opaqueSubMeshes.dispose();
  23148. this._transparentSubMeshes.dispose();
  23149. this._alphaTestSubMeshes.dispose();
  23150. this._depthOnlySubMeshes.dispose();
  23151. this._particleSystems.dispose();
  23152. this._spriteManagers.dispose();
  23153. this._edgesRenderers.dispose();
  23154. };
  23155. /**
  23156. * Inserts the submesh in its correct queue depending on its material.
  23157. * @param subMesh The submesh to dispatch
  23158. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23159. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23160. */
  23161. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23162. // Get mesh and materials if not provided
  23163. if (mesh === undefined) {
  23164. mesh = subMesh.getMesh();
  23165. }
  23166. if (material === undefined) {
  23167. material = subMesh.getMaterial();
  23168. }
  23169. if (material === null || material === undefined) {
  23170. return;
  23171. }
  23172. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23173. this._transparentSubMeshes.push(subMesh);
  23174. }
  23175. else if (material.needAlphaTesting()) { // Alpha test
  23176. if (material.needDepthPrePass) {
  23177. this._depthOnlySubMeshes.push(subMesh);
  23178. }
  23179. this._alphaTestSubMeshes.push(subMesh);
  23180. }
  23181. else {
  23182. if (material.needDepthPrePass) {
  23183. this._depthOnlySubMeshes.push(subMesh);
  23184. }
  23185. this._opaqueSubMeshes.push(subMesh); // Opaque
  23186. }
  23187. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23188. this._edgesRenderers.push(mesh._edgesRenderer);
  23189. }
  23190. };
  23191. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23192. this._spriteManagers.push(spriteManager);
  23193. };
  23194. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23195. this._particleSystems.push(particleSystem);
  23196. };
  23197. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23198. if (this._particleSystems.length === 0) {
  23199. return;
  23200. }
  23201. // Particles
  23202. var activeCamera = this._scene.activeCamera;
  23203. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23204. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23205. var particleSystem = this._particleSystems.data[particleIndex];
  23206. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23207. continue;
  23208. }
  23209. var emitter = particleSystem.emitter;
  23210. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23211. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23212. }
  23213. }
  23214. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23215. };
  23216. RenderingGroup.prototype._renderSprites = function () {
  23217. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23218. return;
  23219. }
  23220. // Sprites
  23221. var activeCamera = this._scene.activeCamera;
  23222. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23223. for (var id = 0; id < this._spriteManagers.length; id++) {
  23224. var spriteManager = this._spriteManagers.data[id];
  23225. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23226. spriteManager.render();
  23227. }
  23228. }
  23229. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23230. };
  23231. return RenderingGroup;
  23232. }());
  23233. BABYLON.RenderingGroup = RenderingGroup;
  23234. })(BABYLON || (BABYLON = {}));
  23235. //# sourceMappingURL=babylon.renderingGroup.js.map
  23236. var BABYLON;
  23237. (function (BABYLON) {
  23238. /**
  23239. * Groups all the scene component constants in one place to ease maintenance.
  23240. * @hidden
  23241. */
  23242. var SceneComponentConstants = /** @class */ (function () {
  23243. function SceneComponentConstants() {
  23244. }
  23245. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23246. SceneComponentConstants.NAME_LAYER = "Layer";
  23247. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23248. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23249. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23250. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23251. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23252. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23253. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23254. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23255. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23256. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23257. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23258. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23259. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23260. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23261. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23262. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23263. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23264. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23265. return SceneComponentConstants;
  23266. }());
  23267. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23268. /**
  23269. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23270. * @hidden
  23271. */
  23272. var Stage = /** @class */ (function (_super) {
  23273. __extends(Stage, _super);
  23274. /**
  23275. * Hide ctor from the rest of the world.
  23276. * @param items The items to add.
  23277. */
  23278. function Stage(items) {
  23279. return _super.apply(this, items) || this;
  23280. }
  23281. /**
  23282. * Creates a new Stage.
  23283. * @returns A new instance of a Stage
  23284. */
  23285. Stage.Create = function () {
  23286. return Object.create(Stage.prototype);
  23287. };
  23288. /**
  23289. * Registers a step in an ordered way in the targeted stage.
  23290. * @param index Defines the position to register the step in
  23291. * @param component Defines the component attached to the step
  23292. * @param action Defines the action to launch during the step
  23293. */
  23294. Stage.prototype.registerStep = function (index, component, action) {
  23295. var i = 0;
  23296. var maxIndex = Number.MAX_VALUE;
  23297. for (; i < this.length && i < maxIndex; i++) {
  23298. var step = this[i];
  23299. maxIndex = step.index;
  23300. }
  23301. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23302. };
  23303. /**
  23304. * Clears all the steps from the stage.
  23305. */
  23306. Stage.prototype.clear = function () {
  23307. this.length = 0;
  23308. };
  23309. return Stage;
  23310. }(Array));
  23311. BABYLON.Stage = Stage;
  23312. })(BABYLON || (BABYLON = {}));
  23313. //# sourceMappingURL=babylon.sceneComponent.js.map
  23314. var BABYLON;
  23315. (function (BABYLON) {
  23316. /**
  23317. * Base class of the scene acting as a container for the different elements composing a scene.
  23318. * This class is dynamically extended by the different components of the scene increasing
  23319. * flexibility and reducing coupling
  23320. */
  23321. var AbstractScene = /** @class */ (function () {
  23322. function AbstractScene() {
  23323. /** All of the cameras added to this scene
  23324. * @see http://doc.babylonjs.com/babylon101/cameras
  23325. */
  23326. this.cameras = new Array();
  23327. /**
  23328. * All of the lights added to this scene
  23329. * @see http://doc.babylonjs.com/babylon101/lights
  23330. */
  23331. this.lights = new Array();
  23332. /**
  23333. * All of the (abstract) meshes added to this scene
  23334. */
  23335. this.meshes = new Array();
  23336. /**
  23337. * The list of skeletons added to the scene
  23338. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23339. */
  23340. this.skeletons = new Array();
  23341. /**
  23342. * All of the particle systems added to this scene
  23343. * @see http://doc.babylonjs.com/babylon101/particles
  23344. */
  23345. this.particleSystems = new Array();
  23346. /**
  23347. * Gets a list of Animations associated with the scene
  23348. */
  23349. this.animations = [];
  23350. /**
  23351. * All of the animation groups added to this scene
  23352. * @see http://doc.babylonjs.com/how_to/group
  23353. */
  23354. this.animationGroups = new Array();
  23355. /**
  23356. * All of the multi-materials added to this scene
  23357. * @see http://doc.babylonjs.com/how_to/multi_materials
  23358. */
  23359. this.multiMaterials = new Array();
  23360. /**
  23361. * All of the materials added to this scene
  23362. * @see http://doc.babylonjs.com/babylon101/materials
  23363. */
  23364. this.materials = new Array();
  23365. /**
  23366. * The list of morph target managers added to the scene
  23367. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23368. */
  23369. this.morphTargetManagers = new Array();
  23370. /**
  23371. * The list of geometries used in the scene.
  23372. */
  23373. this.geometries = new Array();
  23374. /**
  23375. * All of the tranform nodes added to this scene
  23376. * @see http://doc.babylonjs.com/how_to/transformnode
  23377. */
  23378. this.transformNodes = new Array();
  23379. /**
  23380. * ActionManagers available on the scene.
  23381. */
  23382. this.actionManagers = new Array();
  23383. /**
  23384. * Sounds to keep.
  23385. */
  23386. this.sounds = new Array();
  23387. /**
  23388. * Textures to keep.
  23389. */
  23390. this.textures = new Array();
  23391. }
  23392. /**
  23393. * Adds a parser in the list of available ones
  23394. * @param name Defines the name of the parser
  23395. * @param parser Defines the parser to add
  23396. */
  23397. AbstractScene.AddParser = function (name, parser) {
  23398. this._BabylonFileParsers[name] = parser;
  23399. };
  23400. /**
  23401. * Gets a general parser from the list of avaialble ones
  23402. * @param name Defines the name of the parser
  23403. * @returns the requested parser or null
  23404. */
  23405. AbstractScene.GetParser = function (name) {
  23406. if (this._BabylonFileParsers[name]) {
  23407. return this._BabylonFileParsers[name];
  23408. }
  23409. return null;
  23410. };
  23411. /**
  23412. * Adds n individual parser in the list of available ones
  23413. * @param name Defines the name of the parser
  23414. * @param parser Defines the parser to add
  23415. */
  23416. AbstractScene.AddIndividualParser = function (name, parser) {
  23417. this._IndividualBabylonFileParsers[name] = parser;
  23418. };
  23419. /**
  23420. * Gets an individual parser from the list of avaialble ones
  23421. * @param name Defines the name of the parser
  23422. * @returns the requested parser or null
  23423. */
  23424. AbstractScene.GetIndividualParser = function (name) {
  23425. if (this._IndividualBabylonFileParsers[name]) {
  23426. return this._IndividualBabylonFileParsers[name];
  23427. }
  23428. return null;
  23429. };
  23430. /**
  23431. * Parser json data and populate both a scene and its associated container object
  23432. * @param jsonData Defines the data to parse
  23433. * @param scene Defines the scene to parse the data for
  23434. * @param container Defines the container attached to the parsing sequence
  23435. * @param rootUrl Defines the root url of the data
  23436. */
  23437. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23438. for (var parserName in this._BabylonFileParsers) {
  23439. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23440. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23441. }
  23442. }
  23443. };
  23444. /**
  23445. * Stores the list of available parsers in the application.
  23446. */
  23447. AbstractScene._BabylonFileParsers = {};
  23448. /**
  23449. * Stores the list of available individual parsers in the application.
  23450. */
  23451. AbstractScene._IndividualBabylonFileParsers = {};
  23452. return AbstractScene;
  23453. }());
  23454. BABYLON.AbstractScene = AbstractScene;
  23455. })(BABYLON || (BABYLON = {}));
  23456. //# sourceMappingURL=babylon.abstractScene.js.map
  23457. var BABYLON;
  23458. (function (BABYLON) {
  23459. /** @hidden */
  23460. var ClickInfo = /** @class */ (function () {
  23461. function ClickInfo() {
  23462. this._singleClick = false;
  23463. this._doubleClick = false;
  23464. this._hasSwiped = false;
  23465. this._ignore = false;
  23466. }
  23467. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23468. get: function () {
  23469. return this._singleClick;
  23470. },
  23471. set: function (b) {
  23472. this._singleClick = b;
  23473. },
  23474. enumerable: true,
  23475. configurable: true
  23476. });
  23477. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23478. get: function () {
  23479. return this._doubleClick;
  23480. },
  23481. set: function (b) {
  23482. this._doubleClick = b;
  23483. },
  23484. enumerable: true,
  23485. configurable: true
  23486. });
  23487. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23488. get: function () {
  23489. return this._hasSwiped;
  23490. },
  23491. set: function (b) {
  23492. this._hasSwiped = b;
  23493. },
  23494. enumerable: true,
  23495. configurable: true
  23496. });
  23497. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23498. get: function () {
  23499. return this._ignore;
  23500. },
  23501. set: function (b) {
  23502. this._ignore = b;
  23503. },
  23504. enumerable: true,
  23505. configurable: true
  23506. });
  23507. return ClickInfo;
  23508. }());
  23509. /**
  23510. * This class is used by the onRenderingGroupObservable
  23511. */
  23512. var RenderingGroupInfo = /** @class */ (function () {
  23513. function RenderingGroupInfo() {
  23514. }
  23515. return RenderingGroupInfo;
  23516. }());
  23517. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23518. /**
  23519. * Represents a scene to be rendered by the engine.
  23520. * @see http://doc.babylonjs.com/features/scene
  23521. */
  23522. var Scene = /** @class */ (function (_super) {
  23523. __extends(Scene, _super);
  23524. /**
  23525. * Creates a new Scene
  23526. * @param engine defines the engine to use to render this scene
  23527. */
  23528. function Scene(engine) {
  23529. var _this = _super.call(this) || this;
  23530. // Members
  23531. /**
  23532. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23533. */
  23534. _this.autoClear = true;
  23535. /**
  23536. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23537. */
  23538. _this.autoClearDepthAndStencil = true;
  23539. /**
  23540. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23541. */
  23542. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23543. /**
  23544. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23545. */
  23546. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23547. _this._forceWireframe = false;
  23548. _this._forcePointsCloud = 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 before rendering 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.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  23735. /**
  23736. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  23737. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23738. * 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)
  23739. */
  23740. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  23741. // Animations
  23742. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23743. /**
  23744. * 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).
  23745. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23746. */
  23747. _this.onPrePointerObservable = new BABYLON.Observable();
  23748. /**
  23749. * Observable event triggered each time an input event is received from the rendering canvas
  23750. */
  23751. _this.onPointerObservable = new BABYLON.Observable();
  23752. _this._meshPickProceed = false;
  23753. _this._currentPickResult = null;
  23754. _this._previousPickResult = null;
  23755. _this._totalPointersPressed = 0;
  23756. _this._doubleClickOccured = false;
  23757. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23758. _this.cameraToUseForPointers = null;
  23759. _this._pointerX = 0;
  23760. _this._pointerY = 0;
  23761. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23762. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23763. _this._startingPointerTime = 0;
  23764. _this._previousStartingPointerTime = 0;
  23765. _this._pointerCaptures = {};
  23766. // Deterministic lockstep
  23767. _this._timeAccumulator = 0;
  23768. _this._currentStepId = 0;
  23769. _this._currentInternalStep = 0;
  23770. // Keyboard
  23771. /**
  23772. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23773. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23774. */
  23775. _this.onPreKeyboardObservable = new BABYLON.Observable();
  23776. /**
  23777. * Observable event triggered each time an keyboard event is received from the hosting window
  23778. */
  23779. _this.onKeyboardObservable = new BABYLON.Observable();
  23780. // Coordinates system
  23781. _this._useRightHandedSystem = false;
  23782. // Fog
  23783. _this._fogEnabled = true;
  23784. _this._fogMode = Scene.FOGMODE_NONE;
  23785. /**
  23786. * Gets or sets the fog color to use
  23787. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23788. */
  23789. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23790. /**
  23791. * Gets or sets the fog density to use
  23792. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23793. */
  23794. _this.fogDensity = 0.1;
  23795. /**
  23796. * Gets or sets the fog start distance to use
  23797. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23798. */
  23799. _this.fogStart = 0;
  23800. /**
  23801. * Gets or sets the fog end distance to use
  23802. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23803. */
  23804. _this.fogEnd = 1000.0;
  23805. // Lights
  23806. _this._shadowsEnabled = true;
  23807. _this._lightsEnabled = true;
  23808. /** All of the active cameras added to this scene. */
  23809. _this.activeCameras = new Array();
  23810. // Textures
  23811. _this._texturesEnabled = true;
  23812. // Particles
  23813. /**
  23814. * Gets or sets a boolean indicating if particles are enabled on this scene
  23815. */
  23816. _this.particlesEnabled = true;
  23817. // Sprites
  23818. /**
  23819. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23820. */
  23821. _this.spritesEnabled = true;
  23822. /**
  23823. * All of the sprite managers added to this scene
  23824. * @see http://doc.babylonjs.com/babylon101/sprites
  23825. */
  23826. _this.spriteManagers = new Array();
  23827. // Skeletons
  23828. _this._skeletonsEnabled = true;
  23829. // Lens flares
  23830. /**
  23831. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23832. */
  23833. _this.lensFlaresEnabled = true;
  23834. // Collisions
  23835. /**
  23836. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23837. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23838. */
  23839. _this.collisionsEnabled = true;
  23840. /**
  23841. * Defines the gravity applied to this scene (used only for collisions)
  23842. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23843. */
  23844. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23845. // Postprocesses
  23846. /**
  23847. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23848. */
  23849. _this.postProcessesEnabled = true;
  23850. /**
  23851. * The list of postprocesses added to the scene
  23852. */
  23853. _this.postProcesses = new Array();
  23854. // Customs render targets
  23855. /**
  23856. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23857. */
  23858. _this.renderTargetsEnabled = true;
  23859. /**
  23860. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23861. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23862. */
  23863. _this.dumpNextRenderTargets = false;
  23864. /**
  23865. * The list of user defined render targets added to the scene
  23866. */
  23867. _this.customRenderTargets = new Array();
  23868. /**
  23869. * Gets the list of meshes imported to the scene through SceneLoader
  23870. */
  23871. _this.importedMeshesFiles = new Array();
  23872. // Probes
  23873. /**
  23874. * Gets or sets a boolean indicating if probes are enabled on this scene
  23875. */
  23876. _this.probesEnabled = true;
  23877. /**
  23878. * The list of reflection probes added to the scene
  23879. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23880. */
  23881. _this.reflectionProbes = new Array();
  23882. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23883. // Procedural textures
  23884. /**
  23885. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23886. */
  23887. _this.proceduralTexturesEnabled = true;
  23888. /**
  23889. * The list of procedural textures added to the scene
  23890. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23891. */
  23892. _this.proceduralTextures = new Array();
  23893. /**
  23894. * The list of sound tracks added to the scene
  23895. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23896. */
  23897. _this.soundTracks = new Array();
  23898. _this._audioEnabled = true;
  23899. _this._headphone = false;
  23900. // Performance counters
  23901. _this._totalVertices = new BABYLON.PerfCounter();
  23902. /** @hidden */
  23903. _this._activeIndices = new BABYLON.PerfCounter();
  23904. /** @hidden */
  23905. _this._activeParticles = new BABYLON.PerfCounter();
  23906. /** @hidden */
  23907. _this._activeBones = new BABYLON.PerfCounter();
  23908. _this._animationTime = 0;
  23909. /**
  23910. * Gets or sets a general scale for animation speed
  23911. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23912. */
  23913. _this.animationTimeScale = 1;
  23914. _this._renderId = 0;
  23915. _this._executeWhenReadyTimeoutId = -1;
  23916. _this._intermediateRendering = false;
  23917. _this._viewUpdateFlag = -1;
  23918. _this._projectionUpdateFlag = -1;
  23919. _this._alternateViewUpdateFlag = -1;
  23920. _this._alternateProjectionUpdateFlag = -1;
  23921. /** @hidden */
  23922. _this._toBeDisposed = new BABYLON.SmartArray(256);
  23923. _this._activeRequests = new Array();
  23924. _this._pendingData = new Array();
  23925. _this._isDisposed = false;
  23926. /**
  23927. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23928. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23929. */
  23930. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  23931. _this._activeMeshes = new BABYLON.SmartArray(256);
  23932. _this._processedMaterials = new BABYLON.SmartArray(256);
  23933. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23934. /** @hidden */
  23935. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  23936. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23937. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23938. /** @hidden */
  23939. _this._activeAnimatables = new Array();
  23940. _this._transformMatrix = BABYLON.Matrix.Zero();
  23941. _this._useAlternateCameraConfiguration = false;
  23942. _this._alternateRendering = false;
  23943. /**
  23944. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23945. * This is useful if there are more lights that the maximum simulteanous authorized
  23946. */
  23947. _this.requireLightSorting = false;
  23948. _this._depthRenderer = {};
  23949. /**
  23950. * Backing store of defined scene components.
  23951. */
  23952. _this._components = [];
  23953. /**
  23954. * Backing store of defined scene components.
  23955. */
  23956. _this._serializableComponents = [];
  23957. /**
  23958. * List of components to register on the next registration step.
  23959. */
  23960. _this._transientComponents = [];
  23961. /**
  23962. * Defines the actions happening before camera updates.
  23963. */
  23964. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  23965. /**
  23966. * Defines the actions happening during the per mesh ready checks.
  23967. */
  23968. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  23969. /**
  23970. * Defines the actions happening before evaluate active mesh checks.
  23971. */
  23972. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  23973. /**
  23974. * Defines the actions happening during the evaluate sub mesh checks.
  23975. */
  23976. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  23977. /**
  23978. * Defines the actions happening during the active mesh stage.
  23979. */
  23980. _this._activeMeshStage = BABYLON.Stage.Create();
  23981. /**
  23982. * Defines the actions happening during the per camera render target step.
  23983. */
  23984. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  23985. /**
  23986. * Defines the actions happening just before the active camera is drawing.
  23987. */
  23988. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  23989. /**
  23990. * Defines the actions happening just before a rendering group is drawing.
  23991. */
  23992. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  23993. /**
  23994. * Defines the actions happening just after a rendering group has been drawn.
  23995. */
  23996. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  23997. /**
  23998. * Defines the actions happening just after the active camera has been drawn.
  23999. */
  24000. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24001. _this._activeMeshesFrozen = false;
  24002. /** @hidden */
  24003. _this._allowPostProcessClear = true;
  24004. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24005. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24006. _this._engine.scenes.push(_this);
  24007. _this._uid = null;
  24008. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24009. if (BABYLON.PostProcessManager) {
  24010. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24011. }
  24012. if (BABYLON.OutlineRenderer) {
  24013. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24014. }
  24015. if (BABYLON.Tools.IsWindowObjectExist()) {
  24016. _this.attachControl();
  24017. }
  24018. //simplification queue
  24019. if (BABYLON.SimplificationQueue) {
  24020. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24021. }
  24022. //collision coordinator initialization. For now legacy per default.
  24023. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24024. // Uniform Buffer
  24025. _this._createUbo();
  24026. // Default Image processing definition
  24027. if (BABYLON.ImageProcessingConfiguration) {
  24028. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24029. }
  24030. return _this;
  24031. }
  24032. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24033. /** The fog is deactivated */
  24034. get: function () {
  24035. return Scene._FOGMODE_NONE;
  24036. },
  24037. enumerable: true,
  24038. configurable: true
  24039. });
  24040. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24041. /** The fog density is following an exponential function */
  24042. get: function () {
  24043. return Scene._FOGMODE_EXP;
  24044. },
  24045. enumerable: true,
  24046. configurable: true
  24047. });
  24048. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24049. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24050. get: function () {
  24051. return Scene._FOGMODE_EXP2;
  24052. },
  24053. enumerable: true,
  24054. configurable: true
  24055. });
  24056. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24057. /** The fog density is following a linear function. */
  24058. get: function () {
  24059. return Scene._FOGMODE_LINEAR;
  24060. },
  24061. enumerable: true,
  24062. configurable: true
  24063. });
  24064. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24065. /**
  24066. * Texture used in all pbr material as the reflection texture.
  24067. * As in the majority of the scene they are the same (exception for multi room and so on),
  24068. * this is easier to reference from here than from all the materials.
  24069. */
  24070. get: function () {
  24071. return this._environmentTexture;
  24072. },
  24073. /**
  24074. * Texture used in all pbr material as the reflection texture.
  24075. * As in the majority of the scene they are the same (exception for multi room and so on),
  24076. * this is easier to set here than in all the materials.
  24077. */
  24078. set: function (value) {
  24079. if (this._environmentTexture === value) {
  24080. return;
  24081. }
  24082. this._environmentTexture = value;
  24083. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24084. },
  24085. enumerable: true,
  24086. configurable: true
  24087. });
  24088. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24089. /**
  24090. * Default image processing configuration used either in the rendering
  24091. * Forward main pass or through the imageProcessingPostProcess if present.
  24092. * As in the majority of the scene they are the same (exception for multi camera),
  24093. * this is easier to reference from here than from all the materials and post process.
  24094. *
  24095. * No setter as we it is a shared configuration, you can set the values instead.
  24096. */
  24097. get: function () {
  24098. return this._imageProcessingConfiguration;
  24099. },
  24100. enumerable: true,
  24101. configurable: true
  24102. });
  24103. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24104. get: function () {
  24105. return this._forceWireframe;
  24106. },
  24107. /**
  24108. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24109. */
  24110. set: function (value) {
  24111. if (this._forceWireframe === value) {
  24112. return;
  24113. }
  24114. this._forceWireframe = value;
  24115. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24116. },
  24117. enumerable: true,
  24118. configurable: true
  24119. });
  24120. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24121. get: function () {
  24122. return this._forcePointsCloud;
  24123. },
  24124. /**
  24125. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24126. */
  24127. set: function (value) {
  24128. if (this._forcePointsCloud === value) {
  24129. return;
  24130. }
  24131. this._forcePointsCloud = value;
  24132. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24133. },
  24134. enumerable: true,
  24135. configurable: true
  24136. });
  24137. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24138. /**
  24139. * Gets or sets the animation properties override
  24140. */
  24141. get: function () {
  24142. return this._animationPropertiesOverride;
  24143. },
  24144. set: function (value) {
  24145. this._animationPropertiesOverride = value;
  24146. },
  24147. enumerable: true,
  24148. configurable: true
  24149. });
  24150. Object.defineProperty(Scene.prototype, "onDispose", {
  24151. /** Sets a function to be executed when this scene is disposed. */
  24152. set: function (callback) {
  24153. if (this._onDisposeObserver) {
  24154. this.onDisposeObservable.remove(this._onDisposeObserver);
  24155. }
  24156. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24157. },
  24158. enumerable: true,
  24159. configurable: true
  24160. });
  24161. Object.defineProperty(Scene.prototype, "beforeRender", {
  24162. /** Sets a function to be executed before rendering this scene */
  24163. set: function (callback) {
  24164. if (this._onBeforeRenderObserver) {
  24165. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24166. }
  24167. if (callback) {
  24168. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24169. }
  24170. },
  24171. enumerable: true,
  24172. configurable: true
  24173. });
  24174. Object.defineProperty(Scene.prototype, "afterRender", {
  24175. /** Sets a function to be executed after rendering this scene */
  24176. set: function (callback) {
  24177. if (this._onAfterRenderObserver) {
  24178. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24179. }
  24180. if (callback) {
  24181. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24182. }
  24183. },
  24184. enumerable: true,
  24185. configurable: true
  24186. });
  24187. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24188. /** Sets a function to be executed before rendering a camera*/
  24189. set: function (callback) {
  24190. if (this._onBeforeCameraRenderObserver) {
  24191. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24192. }
  24193. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24194. },
  24195. enumerable: true,
  24196. configurable: true
  24197. });
  24198. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24199. /** Sets a function to be executed after rendering a camera*/
  24200. set: function (callback) {
  24201. if (this._onAfterCameraRenderObserver) {
  24202. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24203. }
  24204. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24205. },
  24206. enumerable: true,
  24207. configurable: true
  24208. });
  24209. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24210. /**
  24211. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24212. */
  24213. get: function () {
  24214. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24215. },
  24216. enumerable: true,
  24217. configurable: true
  24218. });
  24219. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24220. get: function () {
  24221. return this._useRightHandedSystem;
  24222. },
  24223. /**
  24224. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24225. */
  24226. set: function (value) {
  24227. if (this._useRightHandedSystem === value) {
  24228. return;
  24229. }
  24230. this._useRightHandedSystem = value;
  24231. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24232. },
  24233. enumerable: true,
  24234. configurable: true
  24235. });
  24236. /**
  24237. * Sets the step Id used by deterministic lock step
  24238. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24239. * @param newStepId defines the step Id
  24240. */
  24241. Scene.prototype.setStepId = function (newStepId) {
  24242. this._currentStepId = newStepId;
  24243. };
  24244. ;
  24245. /**
  24246. * Gets the step Id used by deterministic lock step
  24247. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24248. * @returns the step Id
  24249. */
  24250. Scene.prototype.getStepId = function () {
  24251. return this._currentStepId;
  24252. };
  24253. ;
  24254. /**
  24255. * Gets the internal step used by deterministic lock step
  24256. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24257. * @returns the internal step
  24258. */
  24259. Scene.prototype.getInternalStep = function () {
  24260. return this._currentInternalStep;
  24261. };
  24262. ;
  24263. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24264. get: function () {
  24265. return this._fogEnabled;
  24266. },
  24267. /**
  24268. * Gets or sets a boolean indicating if fog is enabled on this scene
  24269. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24270. */
  24271. set: function (value) {
  24272. if (this._fogEnabled === value) {
  24273. return;
  24274. }
  24275. this._fogEnabled = value;
  24276. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24277. },
  24278. enumerable: true,
  24279. configurable: true
  24280. });
  24281. Object.defineProperty(Scene.prototype, "fogMode", {
  24282. get: function () {
  24283. return this._fogMode;
  24284. },
  24285. /**
  24286. * Gets or sets the fog mode to use
  24287. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24288. */
  24289. set: function (value) {
  24290. if (this._fogMode === value) {
  24291. return;
  24292. }
  24293. this._fogMode = value;
  24294. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24295. },
  24296. enumerable: true,
  24297. configurable: true
  24298. });
  24299. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24300. get: function () {
  24301. return this._shadowsEnabled;
  24302. },
  24303. /**
  24304. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24305. */
  24306. set: function (value) {
  24307. if (this._shadowsEnabled === value) {
  24308. return;
  24309. }
  24310. this._shadowsEnabled = value;
  24311. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24312. },
  24313. enumerable: true,
  24314. configurable: true
  24315. });
  24316. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24317. get: function () {
  24318. return this._lightsEnabled;
  24319. },
  24320. /**
  24321. * Gets or sets a boolean indicating if lights are enabled on this scene
  24322. */
  24323. set: function (value) {
  24324. if (this._lightsEnabled === value) {
  24325. return;
  24326. }
  24327. this._lightsEnabled = value;
  24328. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24329. },
  24330. enumerable: true,
  24331. configurable: true
  24332. });
  24333. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24334. /** The default material used on meshes when no material is affected */
  24335. get: function () {
  24336. if (!this._defaultMaterial) {
  24337. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24338. }
  24339. return this._defaultMaterial;
  24340. },
  24341. /** The default material used on meshes when no material is affected */
  24342. set: function (value) {
  24343. this._defaultMaterial = value;
  24344. },
  24345. enumerable: true,
  24346. configurable: true
  24347. });
  24348. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24349. get: function () {
  24350. return this._texturesEnabled;
  24351. },
  24352. /**
  24353. * Gets or sets a boolean indicating if textures are enabled on this scene
  24354. */
  24355. set: function (value) {
  24356. if (this._texturesEnabled === value) {
  24357. return;
  24358. }
  24359. this._texturesEnabled = value;
  24360. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24361. },
  24362. enumerable: true,
  24363. configurable: true
  24364. });
  24365. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24366. get: function () {
  24367. return this._skeletonsEnabled;
  24368. },
  24369. /**
  24370. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24371. */
  24372. set: function (value) {
  24373. if (this._skeletonsEnabled === value) {
  24374. return;
  24375. }
  24376. this._skeletonsEnabled = value;
  24377. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24378. },
  24379. enumerable: true,
  24380. configurable: true
  24381. });
  24382. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24383. /**
  24384. * Gets the postprocess render pipeline manager
  24385. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24386. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24387. */
  24388. get: function () {
  24389. if (!this._postProcessRenderPipelineManager) {
  24390. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24391. }
  24392. return this._postProcessRenderPipelineManager;
  24393. },
  24394. enumerable: true,
  24395. configurable: true
  24396. });
  24397. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24398. /**
  24399. * Gets the main soundtrack associated with the scene
  24400. */
  24401. get: function () {
  24402. if (!this._mainSoundTrack) {
  24403. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24404. }
  24405. return this._mainSoundTrack;
  24406. },
  24407. enumerable: true,
  24408. configurable: true
  24409. });
  24410. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24411. /** @hidden */
  24412. get: function () {
  24413. return this._alternateRendering;
  24414. },
  24415. enumerable: true,
  24416. configurable: true
  24417. });
  24418. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24419. /**
  24420. * Gets the list of frustum planes (built from the active camera)
  24421. */
  24422. get: function () {
  24423. return this._frustumPlanes;
  24424. },
  24425. enumerable: true,
  24426. configurable: true
  24427. });
  24428. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24429. /**
  24430. * Gets the current geometry buffer associated to the scene.
  24431. */
  24432. get: function () {
  24433. return this._geometryBufferRenderer;
  24434. },
  24435. /**
  24436. * Sets the current geometry buffer for the scene.
  24437. */
  24438. set: function (geometryBufferRenderer) {
  24439. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24440. this._geometryBufferRenderer = geometryBufferRenderer;
  24441. }
  24442. },
  24443. enumerable: true,
  24444. configurable: true
  24445. });
  24446. /**
  24447. * Registers the transient components if needed.
  24448. */
  24449. Scene.prototype._registerTransientComponents = function () {
  24450. // Register components that have been associated lately to the scene.
  24451. if (this._transientComponents.length > 0) {
  24452. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24453. var component = _a[_i];
  24454. component.register();
  24455. }
  24456. this._transientComponents = [];
  24457. }
  24458. };
  24459. /**
  24460. * Add a component to the scene.
  24461. * Note that the ccomponent could be registered on th next frame if this is called after
  24462. * the register component stage.
  24463. * @param component Defines the component to add to the scene
  24464. */
  24465. Scene.prototype._addComponent = function (component) {
  24466. this._components.push(component);
  24467. this._transientComponents.push(component);
  24468. var serializableComponent = component;
  24469. if (serializableComponent.addFromContainer) {
  24470. this._serializableComponents.push(serializableComponent);
  24471. }
  24472. };
  24473. /**
  24474. * Gets a component from the scene.
  24475. * @param name defines the name of the component to retrieve
  24476. * @returns the component or null if not present
  24477. */
  24478. Scene.prototype._getComponent = function (name) {
  24479. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24480. var component = _a[_i];
  24481. if (component.name === name) {
  24482. return component;
  24483. }
  24484. }
  24485. return null;
  24486. };
  24487. Object.defineProperty(Scene.prototype, "debugLayer", {
  24488. /**
  24489. * Gets the debug layer (aka Inspector) associated with the scene
  24490. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24491. */
  24492. get: function () {
  24493. if (!this._debugLayer) {
  24494. this._debugLayer = new BABYLON.DebugLayer(this);
  24495. }
  24496. return this._debugLayer;
  24497. },
  24498. enumerable: true,
  24499. configurable: true
  24500. });
  24501. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24502. /**
  24503. * Gets a boolean indicating if collisions are processed on a web worker
  24504. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24505. */
  24506. get: function () {
  24507. return this._workerCollisions;
  24508. },
  24509. set: function (enabled) {
  24510. if (!BABYLON.CollisionCoordinatorLegacy) {
  24511. return;
  24512. }
  24513. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24514. this._workerCollisions = enabled;
  24515. if (this.collisionCoordinator) {
  24516. this.collisionCoordinator.destroy();
  24517. }
  24518. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24519. this.collisionCoordinator.init(this);
  24520. },
  24521. enumerable: true,
  24522. configurable: true
  24523. });
  24524. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24525. /**
  24526. * Gets the octree used to boost mesh selection (picking)
  24527. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24528. */
  24529. get: function () {
  24530. return this._selectionOctree;
  24531. },
  24532. enumerable: true,
  24533. configurable: true
  24534. });
  24535. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24536. /**
  24537. * Gets the mesh that is currently under the pointer
  24538. */
  24539. get: function () {
  24540. return this._pointerOverMesh;
  24541. },
  24542. enumerable: true,
  24543. configurable: true
  24544. });
  24545. Object.defineProperty(Scene.prototype, "pointerX", {
  24546. /**
  24547. * Gets the current on-screen X position of the pointer
  24548. */
  24549. get: function () {
  24550. return this._pointerX;
  24551. },
  24552. enumerable: true,
  24553. configurable: true
  24554. });
  24555. Object.defineProperty(Scene.prototype, "pointerY", {
  24556. /**
  24557. * Gets the current on-screen Y position of the pointer
  24558. */
  24559. get: function () {
  24560. return this._pointerY;
  24561. },
  24562. enumerable: true,
  24563. configurable: true
  24564. });
  24565. /**
  24566. * Gets the cached material (ie. the latest rendered one)
  24567. * @returns the cached material
  24568. */
  24569. Scene.prototype.getCachedMaterial = function () {
  24570. return this._cachedMaterial;
  24571. };
  24572. /**
  24573. * Gets the cached effect (ie. the latest rendered one)
  24574. * @returns the cached effect
  24575. */
  24576. Scene.prototype.getCachedEffect = function () {
  24577. return this._cachedEffect;
  24578. };
  24579. /**
  24580. * Gets the cached visibility state (ie. the latest rendered one)
  24581. * @returns the cached visibility state
  24582. */
  24583. Scene.prototype.getCachedVisibility = function () {
  24584. return this._cachedVisibility;
  24585. };
  24586. /**
  24587. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24588. * @param material defines the current material
  24589. * @param effect defines the current effect
  24590. * @param visibility defines the current visibility state
  24591. * @returns true if one parameter is not cached
  24592. */
  24593. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24594. if (visibility === void 0) { visibility = 1; }
  24595. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24596. };
  24597. /**
  24598. * Gets the outline renderer associated with the scene
  24599. * @returns a OutlineRenderer
  24600. */
  24601. Scene.prototype.getOutlineRenderer = function () {
  24602. return this._outlineRenderer;
  24603. };
  24604. /**
  24605. * Gets the engine associated with the scene
  24606. * @returns an Engine
  24607. */
  24608. Scene.prototype.getEngine = function () {
  24609. return this._engine;
  24610. };
  24611. /**
  24612. * Gets the total number of vertices rendered per frame
  24613. * @returns the total number of vertices rendered per frame
  24614. */
  24615. Scene.prototype.getTotalVertices = function () {
  24616. return this._totalVertices.current;
  24617. };
  24618. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24619. /**
  24620. * Gets the performance counter for total vertices
  24621. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24622. */
  24623. get: function () {
  24624. return this._totalVertices;
  24625. },
  24626. enumerable: true,
  24627. configurable: true
  24628. });
  24629. /**
  24630. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24631. * @returns the total number of active indices rendered per frame
  24632. */
  24633. Scene.prototype.getActiveIndices = function () {
  24634. return this._activeIndices.current;
  24635. };
  24636. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24637. /**
  24638. * Gets the performance counter for active indices
  24639. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24640. */
  24641. get: function () {
  24642. return this._activeIndices;
  24643. },
  24644. enumerable: true,
  24645. configurable: true
  24646. });
  24647. /**
  24648. * Gets the total number of active particles rendered per frame
  24649. * @returns the total number of active particles rendered per frame
  24650. */
  24651. Scene.prototype.getActiveParticles = function () {
  24652. return this._activeParticles.current;
  24653. };
  24654. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24655. /**
  24656. * Gets the performance counter for active particles
  24657. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24658. */
  24659. get: function () {
  24660. return this._activeParticles;
  24661. },
  24662. enumerable: true,
  24663. configurable: true
  24664. });
  24665. /**
  24666. * Gets the total number of active bones rendered per frame
  24667. * @returns the total number of active bones rendered per frame
  24668. */
  24669. Scene.prototype.getActiveBones = function () {
  24670. return this._activeBones.current;
  24671. };
  24672. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24673. /**
  24674. * Gets the performance counter for active bones
  24675. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24676. */
  24677. get: function () {
  24678. return this._activeBones;
  24679. },
  24680. enumerable: true,
  24681. configurable: true
  24682. });
  24683. /** @hidden */
  24684. Scene.prototype.getInterFramePerfCounter = function () {
  24685. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24686. return 0;
  24687. };
  24688. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24689. /** @hidden */
  24690. get: function () {
  24691. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24692. return null;
  24693. },
  24694. enumerable: true,
  24695. configurable: true
  24696. });
  24697. /** @hidden */
  24698. Scene.prototype.getLastFrameDuration = function () {
  24699. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24700. return 0;
  24701. };
  24702. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24703. /** @hidden */
  24704. get: function () {
  24705. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24706. return null;
  24707. },
  24708. enumerable: true,
  24709. configurable: true
  24710. });
  24711. /** @hidden */
  24712. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24713. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24714. return 0;
  24715. };
  24716. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24717. /** @hidden */
  24718. get: function () {
  24719. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24720. return null;
  24721. },
  24722. enumerable: true,
  24723. configurable: true
  24724. });
  24725. /**
  24726. * Gets the array of active meshes
  24727. * @returns an array of AbstractMesh
  24728. */
  24729. Scene.prototype.getActiveMeshes = function () {
  24730. return this._activeMeshes;
  24731. };
  24732. /** @hidden */
  24733. Scene.prototype.getRenderTargetsDuration = function () {
  24734. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24735. return 0;
  24736. };
  24737. /** @hidden */
  24738. Scene.prototype.getRenderDuration = function () {
  24739. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24740. return 0;
  24741. };
  24742. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24743. /** @hidden */
  24744. get: function () {
  24745. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24746. return null;
  24747. },
  24748. enumerable: true,
  24749. configurable: true
  24750. });
  24751. /** @hidden */
  24752. Scene.prototype.getParticlesDuration = function () {
  24753. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24754. return 0;
  24755. };
  24756. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24757. /** @hidden */
  24758. get: function () {
  24759. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24760. return null;
  24761. },
  24762. enumerable: true,
  24763. configurable: true
  24764. });
  24765. /** @hidden */
  24766. Scene.prototype.getSpritesDuration = function () {
  24767. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24768. return 0;
  24769. };
  24770. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24771. /** @hidden */
  24772. get: function () {
  24773. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24774. return null;
  24775. },
  24776. enumerable: true,
  24777. configurable: true
  24778. });
  24779. /**
  24780. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24781. * @returns a number
  24782. */
  24783. Scene.prototype.getAnimationRatio = function () {
  24784. return this._animationRatio !== undefined ? this._animationRatio : 1;
  24785. };
  24786. /**
  24787. * Gets an unique Id for the current frame
  24788. * @returns a number
  24789. */
  24790. Scene.prototype.getRenderId = function () {
  24791. return this._renderId;
  24792. };
  24793. /** Call this function if you want to manually increment the render Id*/
  24794. Scene.prototype.incrementRenderId = function () {
  24795. this._renderId++;
  24796. };
  24797. Scene.prototype._updatePointerPosition = function (evt) {
  24798. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24799. if (!canvasRect) {
  24800. return;
  24801. }
  24802. this._pointerX = evt.clientX - canvasRect.left;
  24803. this._pointerY = evt.clientY - canvasRect.top;
  24804. this._unTranslatedPointerX = this._pointerX;
  24805. this._unTranslatedPointerY = this._pointerY;
  24806. };
  24807. Scene.prototype._createUbo = function () {
  24808. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24809. this._sceneUbo.addUniform("viewProjection", 16);
  24810. this._sceneUbo.addUniform("view", 16);
  24811. };
  24812. Scene.prototype._createAlternateUbo = function () {
  24813. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24814. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24815. this._alternateSceneUbo.addUniform("view", 16);
  24816. };
  24817. // Pointers handling
  24818. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24819. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24820. if (result) {
  24821. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24822. }
  24823. return result;
  24824. };
  24825. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24826. if (pointerInfo.pickInfo) {
  24827. if (!pointerInfo.pickInfo.ray) {
  24828. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24829. }
  24830. }
  24831. };
  24832. /**
  24833. * Use this method to simulate a pointer move on a mesh
  24834. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24835. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24836. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24837. * @returns the current scene
  24838. */
  24839. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24840. var evt = new PointerEvent("pointermove", pointerEventInit);
  24841. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24842. return this;
  24843. }
  24844. return this._processPointerMove(pickResult, evt);
  24845. };
  24846. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24847. var canvas = this._engine.getRenderingCanvas();
  24848. if (!canvas) {
  24849. return this;
  24850. }
  24851. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24852. this.setPointerOverSprite(null);
  24853. this.setPointerOverMesh(pickResult.pickedMesh);
  24854. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24855. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24856. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24857. }
  24858. else {
  24859. canvas.style.cursor = this.hoverCursor;
  24860. }
  24861. }
  24862. else {
  24863. canvas.style.cursor = this.defaultCursor;
  24864. }
  24865. }
  24866. else {
  24867. this.setPointerOverMesh(null);
  24868. // Sprites
  24869. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24870. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24871. this.setPointerOverSprite(pickResult.pickedSprite);
  24872. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24873. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24874. }
  24875. else {
  24876. canvas.style.cursor = this.hoverCursor;
  24877. }
  24878. }
  24879. else {
  24880. this.setPointerOverSprite(null);
  24881. // Restore pointer
  24882. canvas.style.cursor = this.defaultCursor;
  24883. }
  24884. }
  24885. if (pickResult) {
  24886. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24887. if (this.onPointerMove) {
  24888. this.onPointerMove(evt, pickResult, type);
  24889. }
  24890. if (this.onPointerObservable.hasObservers()) {
  24891. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24892. this._setRayOnPointerInfo(pi);
  24893. this.onPointerObservable.notifyObservers(pi, type);
  24894. }
  24895. }
  24896. return this;
  24897. };
  24898. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  24899. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  24900. if (pickResult) {
  24901. pi.ray = pickResult.ray;
  24902. }
  24903. this.onPrePointerObservable.notifyObservers(pi, type);
  24904. if (pi.skipOnPointerObservable) {
  24905. return true;
  24906. }
  24907. else {
  24908. return false;
  24909. }
  24910. };
  24911. /**
  24912. * Use this method to simulate a pointer down on a mesh
  24913. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24914. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24915. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24916. * @returns the current scene
  24917. */
  24918. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24919. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24920. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  24921. return this;
  24922. }
  24923. return this._processPointerDown(pickResult, evt);
  24924. };
  24925. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24926. var _this = this;
  24927. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24928. this._pickedDownMesh = pickResult.pickedMesh;
  24929. var actionManager = pickResult.pickedMesh.actionManager;
  24930. if (actionManager) {
  24931. if (actionManager.hasPickTriggers) {
  24932. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24933. switch (evt.button) {
  24934. case 0:
  24935. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24936. break;
  24937. case 1:
  24938. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24939. break;
  24940. case 2:
  24941. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24942. break;
  24943. }
  24944. }
  24945. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24946. window.setTimeout(function () {
  24947. 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);
  24948. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24949. if (_this._totalPointersPressed !== 0 &&
  24950. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24951. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24952. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24953. _this._startingPointerTime = 0;
  24954. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24955. }
  24956. }
  24957. }, Scene.LongPressDelay);
  24958. }
  24959. }
  24960. }
  24961. if (pickResult) {
  24962. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24963. if (this.onPointerDown) {
  24964. this.onPointerDown(evt, pickResult, type);
  24965. }
  24966. if (this.onPointerObservable.hasObservers()) {
  24967. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24968. this._setRayOnPointerInfo(pi);
  24969. this.onPointerObservable.notifyObservers(pi, type);
  24970. }
  24971. }
  24972. return this;
  24973. };
  24974. /**
  24975. * Use this method to simulate a pointer up on a mesh
  24976. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24977. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24978. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24979. * @returns the current scene
  24980. */
  24981. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24982. var evt = new PointerEvent("pointerup", pointerEventInit);
  24983. var clickInfo = new ClickInfo();
  24984. clickInfo.singleClick = true;
  24985. clickInfo.ignore = true;
  24986. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  24987. return this;
  24988. }
  24989. return this._processPointerUp(pickResult, evt, clickInfo);
  24990. };
  24991. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24992. if (pickResult && pickResult && pickResult.pickedMesh) {
  24993. this._pickedUpMesh = pickResult.pickedMesh;
  24994. if (this._pickedDownMesh === this._pickedUpMesh) {
  24995. if (this.onPointerPick) {
  24996. this.onPointerPick(evt, pickResult);
  24997. }
  24998. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24999. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25000. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25001. this._setRayOnPointerInfo(pi);
  25002. this.onPointerObservable.notifyObservers(pi, type_1);
  25003. }
  25004. }
  25005. if (pickResult.pickedMesh.actionManager) {
  25006. if (clickInfo.ignore) {
  25007. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25008. }
  25009. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25010. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25011. }
  25012. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25013. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25014. }
  25015. }
  25016. }
  25017. if (this._pickedDownMesh &&
  25018. this._pickedDownMesh.actionManager &&
  25019. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25020. this._pickedDownMesh !== this._pickedUpMesh) {
  25021. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25022. }
  25023. var type = BABYLON.PointerEventTypes.POINTERUP;
  25024. if (this.onPointerObservable.hasObservers()) {
  25025. if (!clickInfo.ignore) {
  25026. if (!clickInfo.hasSwiped) {
  25027. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25028. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25029. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25030. this._setRayOnPointerInfo(pi);
  25031. this.onPointerObservable.notifyObservers(pi, type_2);
  25032. }
  25033. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25034. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25035. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25036. this._setRayOnPointerInfo(pi);
  25037. this.onPointerObservable.notifyObservers(pi, type_3);
  25038. }
  25039. }
  25040. }
  25041. else {
  25042. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25043. this._setRayOnPointerInfo(pi);
  25044. this.onPointerObservable.notifyObservers(pi, type);
  25045. }
  25046. }
  25047. if (this.onPointerUp) {
  25048. this.onPointerUp(evt, pickResult, type);
  25049. }
  25050. return this;
  25051. };
  25052. /**
  25053. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25054. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25055. * @returns true if the pointer was captured
  25056. */
  25057. Scene.prototype.isPointerCaptured = function (pointerId) {
  25058. if (pointerId === void 0) { pointerId = 0; }
  25059. return this._pointerCaptures[pointerId];
  25060. };
  25061. /**
  25062. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25063. * @param attachUp defines if you want to attach events to pointerup
  25064. * @param attachDown defines if you want to attach events to pointerdown
  25065. * @param attachMove defines if you want to attach events to pointermove
  25066. */
  25067. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25068. var _this = this;
  25069. if (attachUp === void 0) { attachUp = true; }
  25070. if (attachDown === void 0) { attachDown = true; }
  25071. if (attachMove === void 0) { attachMove = true; }
  25072. this._initActionManager = function (act, clickInfo) {
  25073. if (!_this._meshPickProceed) {
  25074. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25075. _this._currentPickResult = pickResult;
  25076. if (pickResult) {
  25077. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25078. }
  25079. _this._meshPickProceed = true;
  25080. }
  25081. return act;
  25082. };
  25083. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25084. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25085. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25086. btn !== _this._previousButtonPressed) {
  25087. _this._doubleClickOccured = false;
  25088. clickInfo.singleClick = true;
  25089. clickInfo.ignore = false;
  25090. cb(clickInfo, _this._currentPickResult);
  25091. }
  25092. };
  25093. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25094. var clickInfo = new ClickInfo();
  25095. _this._currentPickResult = null;
  25096. var act = null;
  25097. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25098. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25099. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25100. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25101. act = _this._initActionManager(act, clickInfo);
  25102. if (act)
  25103. checkPicking = act.hasPickTriggers;
  25104. }
  25105. if (checkPicking) {
  25106. var btn = evt.button;
  25107. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25108. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25109. if (!clickInfo.hasSwiped) {
  25110. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25111. if (!checkSingleClickImmediately) {
  25112. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25113. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25114. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25115. act = _this._initActionManager(act, clickInfo);
  25116. if (act)
  25117. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25118. }
  25119. }
  25120. if (checkSingleClickImmediately) {
  25121. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25122. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25123. btn !== _this._previousButtonPressed) {
  25124. clickInfo.singleClick = true;
  25125. cb(clickInfo, _this._currentPickResult);
  25126. }
  25127. }
  25128. // at least one double click is required to be check and exclusive double click is enabled
  25129. else {
  25130. // wait that no double click has been raised during the double click delay
  25131. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25132. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25133. }
  25134. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25135. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25136. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25137. act = _this._initActionManager(act, clickInfo);
  25138. if (act)
  25139. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25140. }
  25141. if (checkDoubleClick) {
  25142. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25143. if (btn === _this._previousButtonPressed &&
  25144. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25145. !_this._doubleClickOccured) {
  25146. // pointer has not moved for 2 clicks, it's a double click
  25147. if (!clickInfo.hasSwiped &&
  25148. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25149. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25150. _this._previousStartingPointerTime = 0;
  25151. _this._doubleClickOccured = true;
  25152. clickInfo.doubleClick = true;
  25153. clickInfo.ignore = false;
  25154. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25155. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25156. }
  25157. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25158. cb(clickInfo, _this._currentPickResult);
  25159. }
  25160. // if the two successive clicks are too far, it's just two simple clicks
  25161. else {
  25162. _this._doubleClickOccured = false;
  25163. _this._previousStartingPointerTime = _this._startingPointerTime;
  25164. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25165. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25166. _this._previousButtonPressed = btn;
  25167. if (Scene.ExclusiveDoubleClickMode) {
  25168. if (_this._previousDelayedSimpleClickTimeout) {
  25169. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25170. }
  25171. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25172. cb(clickInfo, _this._previousPickResult);
  25173. }
  25174. else {
  25175. cb(clickInfo, _this._currentPickResult);
  25176. }
  25177. }
  25178. }
  25179. // just the first click of the double has been raised
  25180. else {
  25181. _this._doubleClickOccured = false;
  25182. _this._previousStartingPointerTime = _this._startingPointerTime;
  25183. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25184. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25185. _this._previousButtonPressed = btn;
  25186. }
  25187. }
  25188. }
  25189. }
  25190. clickInfo.ignore = true;
  25191. cb(clickInfo, _this._currentPickResult);
  25192. };
  25193. this._spritePredicate = function (sprite) {
  25194. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25195. };
  25196. this._onPointerMove = function (evt) {
  25197. _this._updatePointerPosition(evt);
  25198. // PreObservable support
  25199. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25200. return;
  25201. }
  25202. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25203. return;
  25204. }
  25205. if (!_this.pointerMovePredicate) {
  25206. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25207. }
  25208. // Meshes
  25209. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25210. _this._processPointerMove(pickResult, evt);
  25211. };
  25212. this._onPointerDown = function (evt) {
  25213. _this._totalPointersPressed++;
  25214. _this._pickedDownMesh = null;
  25215. _this._meshPickProceed = false;
  25216. _this._updatePointerPosition(evt);
  25217. if (_this.preventDefaultOnPointerDown && canvas) {
  25218. evt.preventDefault();
  25219. canvas.focus();
  25220. }
  25221. // PreObservable support
  25222. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25223. return;
  25224. }
  25225. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25226. return;
  25227. }
  25228. _this._pointerCaptures[evt.pointerId] = true;
  25229. _this._startingPointerPosition.x = _this._pointerX;
  25230. _this._startingPointerPosition.y = _this._pointerY;
  25231. _this._startingPointerTime = Date.now();
  25232. if (!_this.pointerDownPredicate) {
  25233. _this.pointerDownPredicate = function (mesh) {
  25234. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25235. };
  25236. }
  25237. // Meshes
  25238. _this._pickedDownMesh = null;
  25239. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25240. _this._processPointerDown(pickResult, evt);
  25241. // Sprites
  25242. _this._pickedDownSprite = null;
  25243. if (_this.spriteManagers.length > 0) {
  25244. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25245. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25246. if (pickResult.pickedSprite.actionManager) {
  25247. _this._pickedDownSprite = pickResult.pickedSprite;
  25248. switch (evt.button) {
  25249. case 0:
  25250. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25251. break;
  25252. case 1:
  25253. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25254. break;
  25255. case 2:
  25256. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25257. break;
  25258. }
  25259. if (pickResult.pickedSprite.actionManager) {
  25260. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25261. }
  25262. }
  25263. }
  25264. }
  25265. };
  25266. this._onPointerUp = function (evt) {
  25267. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25268. return; // So we need to test it the pointer down was pressed before.
  25269. }
  25270. _this._totalPointersPressed--;
  25271. _this._pickedUpMesh = null;
  25272. _this._meshPickProceed = false;
  25273. _this._updatePointerPosition(evt);
  25274. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25275. // PreObservable support
  25276. if (_this.onPrePointerObservable.hasObservers()) {
  25277. if (!clickInfo.ignore) {
  25278. if (!clickInfo.hasSwiped) {
  25279. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25280. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25281. return;
  25282. }
  25283. }
  25284. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25285. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25286. return;
  25287. }
  25288. }
  25289. }
  25290. }
  25291. else {
  25292. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25293. return;
  25294. }
  25295. }
  25296. }
  25297. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25298. return;
  25299. }
  25300. _this._pointerCaptures[evt.pointerId] = false;
  25301. if (!_this.pointerUpPredicate) {
  25302. _this.pointerUpPredicate = function (mesh) {
  25303. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25304. };
  25305. }
  25306. // Meshes
  25307. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25308. _this._initActionManager(null, clickInfo);
  25309. }
  25310. if (!pickResult) {
  25311. pickResult = _this._currentPickResult;
  25312. }
  25313. _this._processPointerUp(pickResult, evt, clickInfo);
  25314. // Sprites
  25315. if (!clickInfo.ignore) {
  25316. if (_this.spriteManagers.length > 0) {
  25317. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25318. if (spritePickResult) {
  25319. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25320. if (spritePickResult.pickedSprite.actionManager) {
  25321. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25322. if (spritePickResult.pickedSprite.actionManager) {
  25323. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25324. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25325. }
  25326. }
  25327. }
  25328. }
  25329. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25330. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25331. }
  25332. }
  25333. }
  25334. }
  25335. _this._previousPickResult = _this._currentPickResult;
  25336. });
  25337. };
  25338. this._onKeyDown = function (evt) {
  25339. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25340. if (_this.onPreKeyboardObservable.hasObservers()) {
  25341. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25342. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25343. if (pi.skipOnPointerObservable) {
  25344. return;
  25345. }
  25346. }
  25347. if (_this.onKeyboardObservable.hasObservers()) {
  25348. var pi = new BABYLON.KeyboardInfo(type, evt);
  25349. _this.onKeyboardObservable.notifyObservers(pi, type);
  25350. }
  25351. if (_this.actionManager) {
  25352. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25353. }
  25354. };
  25355. this._onKeyUp = function (evt) {
  25356. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25357. if (_this.onPreKeyboardObservable.hasObservers()) {
  25358. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25359. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25360. if (pi.skipOnPointerObservable) {
  25361. return;
  25362. }
  25363. }
  25364. if (_this.onKeyboardObservable.hasObservers()) {
  25365. var pi = new BABYLON.KeyboardInfo(type, evt);
  25366. _this.onKeyboardObservable.notifyObservers(pi, type);
  25367. }
  25368. if (_this.actionManager) {
  25369. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25370. }
  25371. };
  25372. var engine = this.getEngine();
  25373. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25374. if (!canvas) {
  25375. return;
  25376. }
  25377. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25378. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25379. });
  25380. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25381. if (!canvas) {
  25382. return;
  25383. }
  25384. canvas.removeEventListener("keydown", _this._onKeyDown);
  25385. canvas.removeEventListener("keyup", _this._onKeyUp);
  25386. });
  25387. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25388. var canvas = this._engine.getRenderingCanvas();
  25389. if (!canvas) {
  25390. return;
  25391. }
  25392. if (attachMove) {
  25393. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25394. // Wheel
  25395. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25396. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25397. }
  25398. if (attachDown) {
  25399. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25400. }
  25401. if (attachUp) {
  25402. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25403. }
  25404. canvas.tabIndex = 1;
  25405. };
  25406. /** Detaches all event handlers*/
  25407. Scene.prototype.detachControl = function () {
  25408. var engine = this.getEngine();
  25409. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25410. var canvas = engine.getRenderingCanvas();
  25411. if (!canvas) {
  25412. return;
  25413. }
  25414. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25415. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25416. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25417. if (this._onCanvasBlurObserver) {
  25418. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25419. }
  25420. if (this._onCanvasFocusObserver) {
  25421. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25422. }
  25423. // Wheel
  25424. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25425. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25426. // Keyboard
  25427. canvas.removeEventListener("keydown", this._onKeyDown);
  25428. canvas.removeEventListener("keyup", this._onKeyUp);
  25429. // Observables
  25430. this.onKeyboardObservable.clear();
  25431. this.onPreKeyboardObservable.clear();
  25432. this.onPointerObservable.clear();
  25433. this.onPrePointerObservable.clear();
  25434. };
  25435. /**
  25436. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25437. * Delay loaded resources are not taking in account
  25438. * @return true if all required resources are ready
  25439. */
  25440. Scene.prototype.isReady = function () {
  25441. if (this._isDisposed) {
  25442. return false;
  25443. }
  25444. if (this._pendingData.length > 0) {
  25445. return false;
  25446. }
  25447. var index;
  25448. var engine = this.getEngine();
  25449. // Geometries
  25450. for (index = 0; index < this.geometries.length; index++) {
  25451. var geometry = this.geometries[index];
  25452. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25453. return false;
  25454. }
  25455. }
  25456. // Meshes
  25457. for (index = 0; index < this.meshes.length; index++) {
  25458. var mesh = this.meshes[index];
  25459. if (!mesh.isEnabled()) {
  25460. continue;
  25461. }
  25462. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25463. continue;
  25464. }
  25465. if (!mesh.isReady(true)) {
  25466. return false;
  25467. }
  25468. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25469. // Is Ready For Mesh
  25470. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25471. var step = _a[_i];
  25472. if (!step.action(mesh, hardwareInstancedRendering)) {
  25473. return false;
  25474. }
  25475. }
  25476. }
  25477. // Post-processes
  25478. if (this.activeCameras && this.activeCameras.length > 0) {
  25479. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25480. var camera = _c[_b];
  25481. if (!camera.isReady(true)) {
  25482. return false;
  25483. }
  25484. }
  25485. }
  25486. else if (this.activeCamera) {
  25487. if (!this.activeCamera.isReady(true)) {
  25488. return false;
  25489. }
  25490. }
  25491. // Particles
  25492. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25493. var particleSystem = _e[_d];
  25494. if (!particleSystem.isReady()) {
  25495. return false;
  25496. }
  25497. }
  25498. return true;
  25499. };
  25500. /** Resets all cached information relative to material (including effect and visibility) */
  25501. Scene.prototype.resetCachedMaterial = function () {
  25502. this._cachedMaterial = null;
  25503. this._cachedEffect = null;
  25504. this._cachedVisibility = null;
  25505. };
  25506. /**
  25507. * Registers a function to be called before every frame render
  25508. * @param func defines the function to register
  25509. */
  25510. Scene.prototype.registerBeforeRender = function (func) {
  25511. this.onBeforeRenderObservable.add(func);
  25512. };
  25513. /**
  25514. * Unregisters a function called before every frame render
  25515. * @param func defines the function to unregister
  25516. */
  25517. Scene.prototype.unregisterBeforeRender = function (func) {
  25518. this.onBeforeRenderObservable.removeCallback(func);
  25519. };
  25520. /**
  25521. * Registers a function to be called after every frame render
  25522. * @param func defines the function to register
  25523. */
  25524. Scene.prototype.registerAfterRender = function (func) {
  25525. this.onAfterRenderObservable.add(func);
  25526. };
  25527. /**
  25528. * Unregisters a function called after every frame render
  25529. * @param func defines the function to unregister
  25530. */
  25531. Scene.prototype.unregisterAfterRender = function (func) {
  25532. this.onAfterRenderObservable.removeCallback(func);
  25533. };
  25534. Scene.prototype._executeOnceBeforeRender = function (func) {
  25535. var _this = this;
  25536. var execFunc = function () {
  25537. func();
  25538. setTimeout(function () {
  25539. _this.unregisterBeforeRender(execFunc);
  25540. });
  25541. };
  25542. this.registerBeforeRender(execFunc);
  25543. };
  25544. /**
  25545. * The provided function will run before render once and will be disposed afterwards.
  25546. * A timeout delay can be provided so that the function will be executed in N ms.
  25547. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25548. * @param func The function to be executed.
  25549. * @param timeout optional delay in ms
  25550. */
  25551. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25552. var _this = this;
  25553. if (timeout !== undefined) {
  25554. setTimeout(function () {
  25555. _this._executeOnceBeforeRender(func);
  25556. }, timeout);
  25557. }
  25558. else {
  25559. this._executeOnceBeforeRender(func);
  25560. }
  25561. };
  25562. /** @hidden */
  25563. Scene.prototype._addPendingData = function (data) {
  25564. this._pendingData.push(data);
  25565. };
  25566. /** @hidden */
  25567. Scene.prototype._removePendingData = function (data) {
  25568. var wasLoading = this.isLoading;
  25569. var index = this._pendingData.indexOf(data);
  25570. if (index !== -1) {
  25571. this._pendingData.splice(index, 1);
  25572. }
  25573. if (wasLoading && !this.isLoading) {
  25574. this.onDataLoadedObservable.notifyObservers(this);
  25575. }
  25576. };
  25577. /**
  25578. * Returns the number of items waiting to be loaded
  25579. * @returns the number of items waiting to be loaded
  25580. */
  25581. Scene.prototype.getWaitingItemsCount = function () {
  25582. return this._pendingData.length;
  25583. };
  25584. Object.defineProperty(Scene.prototype, "isLoading", {
  25585. /**
  25586. * Returns a boolean indicating if the scene is still loading data
  25587. */
  25588. get: function () {
  25589. return this._pendingData.length > 0;
  25590. },
  25591. enumerable: true,
  25592. configurable: true
  25593. });
  25594. /**
  25595. * Registers a function to be executed when the scene is ready
  25596. * @param {Function} func - the function to be executed
  25597. */
  25598. Scene.prototype.executeWhenReady = function (func) {
  25599. var _this = this;
  25600. this.onReadyObservable.add(func);
  25601. if (this._executeWhenReadyTimeoutId !== -1) {
  25602. return;
  25603. }
  25604. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25605. _this._checkIsReady();
  25606. }, 150);
  25607. };
  25608. /**
  25609. * Returns a promise that resolves when the scene is ready
  25610. * @returns A promise that resolves when the scene is ready
  25611. */
  25612. Scene.prototype.whenReadyAsync = function () {
  25613. var _this = this;
  25614. return new Promise(function (resolve) {
  25615. _this.executeWhenReady(function () {
  25616. resolve();
  25617. });
  25618. });
  25619. };
  25620. /** @hidden */
  25621. Scene.prototype._checkIsReady = function () {
  25622. var _this = this;
  25623. this._registerTransientComponents();
  25624. if (this.isReady()) {
  25625. this.onReadyObservable.notifyObservers(this);
  25626. this.onReadyObservable.clear();
  25627. this._executeWhenReadyTimeoutId = -1;
  25628. return;
  25629. }
  25630. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25631. _this._checkIsReady();
  25632. }, 150);
  25633. };
  25634. // Animations
  25635. /**
  25636. * Will start the animation sequence of a given target
  25637. * @param target defines the target
  25638. * @param from defines from which frame should animation start
  25639. * @param to defines until which frame should animation run.
  25640. * @param weight defines the weight to apply to the animation (1.0 by default)
  25641. * @param loop defines if the animation loops
  25642. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25643. * @param onAnimationEnd defines the function to be executed when the animation ends
  25644. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25645. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25646. * @returns the animatable object created for this animation
  25647. */
  25648. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25649. if (weight === void 0) { weight = 1.0; }
  25650. if (speedRatio === void 0) { speedRatio = 1.0; }
  25651. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25652. returnedAnimatable.weight = weight;
  25653. return returnedAnimatable;
  25654. };
  25655. /**
  25656. * Will start the animation sequence of a given target
  25657. * @param target defines the target
  25658. * @param from defines from which frame should animation start
  25659. * @param to defines until which frame should animation run.
  25660. * @param loop defines if the animation loops
  25661. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25662. * @param onAnimationEnd defines the function to be executed when the animation ends
  25663. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25664. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25665. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25666. * @returns the animatable object created for this animation
  25667. */
  25668. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25669. if (speedRatio === void 0) { speedRatio = 1.0; }
  25670. if (stopCurrent === void 0) { stopCurrent = true; }
  25671. if (from > to && speedRatio > 0) {
  25672. speedRatio *= -1;
  25673. }
  25674. if (stopCurrent) {
  25675. this.stopAnimation(target, undefined, targetMask);
  25676. }
  25677. if (!animatable) {
  25678. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25679. }
  25680. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25681. // Local animations
  25682. if (target.animations && shouldRunTargetAnimations) {
  25683. animatable.appendAnimations(target, target.animations);
  25684. }
  25685. // Children animations
  25686. if (target.getAnimatables) {
  25687. var animatables = target.getAnimatables();
  25688. for (var index = 0; index < animatables.length; index++) {
  25689. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25690. }
  25691. }
  25692. animatable.reset();
  25693. return animatable;
  25694. };
  25695. /**
  25696. * Begin a new animation on a given node
  25697. * @param target defines the target where the animation will take place
  25698. * @param animations defines the list of animations to start
  25699. * @param from defines the initial value
  25700. * @param to defines the final value
  25701. * @param loop defines if you want animation to loop (off by default)
  25702. * @param speedRatio defines the speed ratio to apply to all animations
  25703. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25704. * @returns the list of created animatables
  25705. */
  25706. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25707. if (speedRatio === undefined) {
  25708. speedRatio = 1.0;
  25709. }
  25710. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25711. return animatable;
  25712. };
  25713. /**
  25714. * Begin a new animation on a given node and its hierarchy
  25715. * @param target defines the root node where the animation will take place
  25716. * @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.
  25717. * @param animations defines the list of animations to start
  25718. * @param from defines the initial value
  25719. * @param to defines the final value
  25720. * @param loop defines if you want animation to loop (off by default)
  25721. * @param speedRatio defines the speed ratio to apply to all animations
  25722. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25723. * @returns the list of animatables created for all nodes
  25724. */
  25725. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25726. var children = target.getDescendants(directDescendantsOnly);
  25727. var result = [];
  25728. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25729. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25730. var child = children_1[_i];
  25731. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25732. }
  25733. return result;
  25734. };
  25735. /**
  25736. * Gets the animatable associated with a specific target
  25737. * @param target defines the target of the animatable
  25738. * @returns the required animatable if found
  25739. */
  25740. Scene.prototype.getAnimatableByTarget = function (target) {
  25741. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25742. if (this._activeAnimatables[index].target === target) {
  25743. return this._activeAnimatables[index];
  25744. }
  25745. }
  25746. return null;
  25747. };
  25748. /**
  25749. * Gets all animatables associated with a given target
  25750. * @param target defines the target to look animatables for
  25751. * @returns an array of Animatables
  25752. */
  25753. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25754. var result = [];
  25755. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25756. if (this._activeAnimatables[index].target === target) {
  25757. result.push(this._activeAnimatables[index]);
  25758. }
  25759. }
  25760. return result;
  25761. };
  25762. Object.defineProperty(Scene.prototype, "animatables", {
  25763. /**
  25764. * Gets all animatable attached to the scene
  25765. */
  25766. get: function () {
  25767. return this._activeAnimatables;
  25768. },
  25769. enumerable: true,
  25770. configurable: true
  25771. });
  25772. /**
  25773. * Will stop the animation of the given target
  25774. * @param target - the target
  25775. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  25776. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  25777. */
  25778. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  25779. var animatables = this.getAllAnimatablesByTarget(target);
  25780. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25781. var animatable = animatables_1[_i];
  25782. animatable.stop(animationName, targetMask);
  25783. }
  25784. };
  25785. /**
  25786. * Stops and removes all animations that have been applied to the scene
  25787. */
  25788. Scene.prototype.stopAllAnimations = function () {
  25789. if (this._activeAnimatables) {
  25790. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25791. this._activeAnimatables[i].stop();
  25792. }
  25793. this._activeAnimatables = [];
  25794. }
  25795. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25796. var group = _a[_i];
  25797. group.stop();
  25798. }
  25799. };
  25800. Scene.prototype._animate = function () {
  25801. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25802. return;
  25803. }
  25804. // Getting time
  25805. var now = BABYLON.Tools.Now;
  25806. if (!this._animationTimeLast) {
  25807. if (this._pendingData.length > 0) {
  25808. return;
  25809. }
  25810. this._animationTimeLast = now;
  25811. }
  25812. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25813. this._animationTime += deltaTime;
  25814. this._animationTimeLast = now;
  25815. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25816. this._activeAnimatables[index]._animate(this._animationTime);
  25817. }
  25818. // Late animation bindings
  25819. this._processLateAnimationBindings();
  25820. };
  25821. /** @hidden */
  25822. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25823. var target = runtimeAnimation.target;
  25824. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25825. if (!target._lateAnimationHolders) {
  25826. target._lateAnimationHolders = {};
  25827. }
  25828. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25829. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25830. totalWeight: 0,
  25831. animations: [],
  25832. originalValue: originalValue
  25833. };
  25834. }
  25835. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25836. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25837. };
  25838. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25839. var normalizer = 1.0;
  25840. var finalPosition = BABYLON.Tmp.Vector3[0];
  25841. var finalScaling = BABYLON.Tmp.Vector3[1];
  25842. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25843. var startIndex = 0;
  25844. var originalAnimation = holder.animations[0];
  25845. var originalValue = holder.originalValue;
  25846. var scale = 1;
  25847. if (holder.totalWeight < 1.0) {
  25848. // We need to mix the original value in
  25849. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25850. scale = 1.0 - holder.totalWeight;
  25851. }
  25852. else {
  25853. startIndex = 1;
  25854. // We need to normalize the weights
  25855. normalizer = holder.totalWeight;
  25856. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25857. scale = originalAnimation.weight / normalizer;
  25858. if (scale == 1) {
  25859. return originalAnimation.currentValue;
  25860. }
  25861. }
  25862. finalScaling.scaleInPlace(scale);
  25863. finalPosition.scaleInPlace(scale);
  25864. finalQuaternion.scaleInPlace(scale);
  25865. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25866. var runtimeAnimation = holder.animations[animIndex];
  25867. var scale = runtimeAnimation.weight / normalizer;
  25868. var currentPosition = BABYLON.Tmp.Vector3[2];
  25869. var currentScaling = BABYLON.Tmp.Vector3[3];
  25870. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25871. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25872. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25873. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25874. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25875. }
  25876. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25877. return originalAnimation._workValue;
  25878. };
  25879. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25880. var originalAnimation = holder.animations[0];
  25881. var originalValue = holder.originalValue;
  25882. if (holder.animations.length === 1) {
  25883. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25884. }
  25885. var normalizer = 1.0;
  25886. var quaternions;
  25887. var weights;
  25888. if (holder.totalWeight < 1.0) {
  25889. var scale = 1.0 - holder.totalWeight;
  25890. quaternions = [];
  25891. weights = [];
  25892. quaternions.push(originalValue);
  25893. weights.push(scale);
  25894. }
  25895. else {
  25896. if (holder.animations.length === 2) { // Slerp as soon as we can
  25897. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25898. }
  25899. quaternions = [];
  25900. weights = [];
  25901. normalizer = holder.totalWeight;
  25902. }
  25903. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25904. var runtimeAnimation = holder.animations[animIndex];
  25905. quaternions.push(runtimeAnimation.currentValue);
  25906. weights.push(runtimeAnimation.weight / normalizer);
  25907. }
  25908. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25909. var cumulativeAmount = 0;
  25910. var cumulativeQuaternion = null;
  25911. for (var index = 0; index < quaternions.length;) {
  25912. if (!cumulativeQuaternion) {
  25913. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25914. cumulativeAmount = weights[index] + weights[index + 1];
  25915. index += 2;
  25916. continue;
  25917. }
  25918. cumulativeAmount += weights[index];
  25919. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25920. index++;
  25921. }
  25922. return cumulativeQuaternion;
  25923. };
  25924. Scene.prototype._processLateAnimationBindings = function () {
  25925. if (!this._registeredForLateAnimationBindings.length) {
  25926. return;
  25927. }
  25928. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25929. var target = this._registeredForLateAnimationBindings.data[index];
  25930. for (var path in target._lateAnimationHolders) {
  25931. var holder = target._lateAnimationHolders[path];
  25932. var originalAnimation = holder.animations[0];
  25933. var originalValue = holder.originalValue;
  25934. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25935. var finalValue = void 0;
  25936. if (matrixDecomposeMode) {
  25937. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  25938. }
  25939. else {
  25940. var quaternionMode = originalValue.w !== undefined;
  25941. if (quaternionMode) {
  25942. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  25943. }
  25944. else {
  25945. var startIndex = 0;
  25946. var normalizer = 1.0;
  25947. if (holder.totalWeight < 1.0) {
  25948. // We need to mix the original value in
  25949. if (originalValue.scale) {
  25950. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25951. }
  25952. else {
  25953. finalValue = originalValue * (1.0 - holder.totalWeight);
  25954. }
  25955. }
  25956. else {
  25957. // We need to normalize the weights
  25958. normalizer = holder.totalWeight;
  25959. var scale_1 = originalAnimation.weight / normalizer;
  25960. if (scale_1 !== 1) {
  25961. if (originalAnimation.currentValue.scale) {
  25962. finalValue = originalAnimation.currentValue.scale(scale_1);
  25963. }
  25964. else {
  25965. finalValue = originalAnimation.currentValue * scale_1;
  25966. }
  25967. }
  25968. else {
  25969. finalValue = originalAnimation.currentValue;
  25970. }
  25971. startIndex = 1;
  25972. }
  25973. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25974. var runtimeAnimation = holder.animations[animIndex];
  25975. var scale = runtimeAnimation.weight / normalizer;
  25976. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25977. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25978. }
  25979. else {
  25980. finalValue += runtimeAnimation.currentValue * scale;
  25981. }
  25982. }
  25983. }
  25984. }
  25985. target[path] = finalValue;
  25986. }
  25987. target._lateAnimationHolders = {};
  25988. }
  25989. this._registeredForLateAnimationBindings.reset();
  25990. };
  25991. // Matrix
  25992. /** @hidden */
  25993. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25994. this._useAlternateCameraConfiguration = active;
  25995. };
  25996. /**
  25997. * Gets the current view matrix
  25998. * @returns a Matrix
  25999. */
  26000. Scene.prototype.getViewMatrix = function () {
  26001. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26002. };
  26003. /**
  26004. * Gets the current projection matrix
  26005. * @returns a Matrix
  26006. */
  26007. Scene.prototype.getProjectionMatrix = function () {
  26008. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26009. };
  26010. /**
  26011. * Gets the current transform matrix
  26012. * @returns a Matrix made of View * Projection
  26013. */
  26014. Scene.prototype.getTransformMatrix = function () {
  26015. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26016. };
  26017. /**
  26018. * Sets the current transform matrix
  26019. * @param view defines the View matrix to use
  26020. * @param projection defines the Projection matrix to use
  26021. */
  26022. Scene.prototype.setTransformMatrix = function (view, projection) {
  26023. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26024. return;
  26025. }
  26026. this._viewUpdateFlag = view.updateFlag;
  26027. this._projectionUpdateFlag = projection.updateFlag;
  26028. this._viewMatrix = view;
  26029. this._projectionMatrix = projection;
  26030. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26031. // Update frustum
  26032. if (!this._frustumPlanes) {
  26033. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26034. }
  26035. else {
  26036. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26037. }
  26038. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26039. var otherCamera = this.activeCamera._alternateCamera;
  26040. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26041. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26042. }
  26043. if (this._sceneUbo.useUbo) {
  26044. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26045. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26046. this._sceneUbo.update();
  26047. }
  26048. };
  26049. /** @hidden */
  26050. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26051. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26052. return;
  26053. }
  26054. this._alternateViewUpdateFlag = view.updateFlag;
  26055. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26056. this._alternateViewMatrix = view;
  26057. this._alternateProjectionMatrix = projection;
  26058. if (!this._alternateTransformMatrix) {
  26059. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26060. }
  26061. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26062. if (!this._alternateSceneUbo) {
  26063. this._createAlternateUbo();
  26064. }
  26065. if (this._alternateSceneUbo.useUbo) {
  26066. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26067. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26068. this._alternateSceneUbo.update();
  26069. }
  26070. };
  26071. /**
  26072. * Gets the uniform buffer used to store scene data
  26073. * @returns a UniformBuffer
  26074. */
  26075. Scene.prototype.getSceneUniformBuffer = function () {
  26076. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26077. };
  26078. /**
  26079. * Gets an unique (relatively to the current scene) Id
  26080. * @returns an unique number for the scene
  26081. */
  26082. Scene.prototype.getUniqueId = function () {
  26083. var result = Scene._uniqueIdCounter;
  26084. Scene._uniqueIdCounter++;
  26085. return result;
  26086. };
  26087. /**
  26088. * Add a mesh to the list of scene's meshes
  26089. * @param newMesh defines the mesh to add
  26090. * @param recursive if all child meshes should also be added to the scene
  26091. */
  26092. Scene.prototype.addMesh = function (newMesh, recursive) {
  26093. var _this = this;
  26094. if (recursive === void 0) { recursive = false; }
  26095. this.meshes.push(newMesh);
  26096. //notify the collision coordinator
  26097. if (this.collisionCoordinator) {
  26098. this.collisionCoordinator.onMeshAdded(newMesh);
  26099. }
  26100. newMesh._resyncLightSources();
  26101. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26102. if (recursive) {
  26103. newMesh.getChildMeshes().forEach(function (m) {
  26104. _this.addMesh(m);
  26105. });
  26106. }
  26107. };
  26108. /**
  26109. * Remove a mesh for the list of scene's meshes
  26110. * @param toRemove defines the mesh to remove
  26111. * @param recursive if all child meshes should also be removed from the scene
  26112. * @returns the index where the mesh was in the mesh list
  26113. */
  26114. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26115. var _this = this;
  26116. if (recursive === void 0) { recursive = false; }
  26117. var index = this.meshes.indexOf(toRemove);
  26118. if (index !== -1) {
  26119. // Remove from the scene if mesh found
  26120. this.meshes.splice(index, 1);
  26121. }
  26122. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26123. if (recursive) {
  26124. toRemove.getChildMeshes().forEach(function (m) {
  26125. _this.removeMesh(m);
  26126. });
  26127. }
  26128. return index;
  26129. };
  26130. /**
  26131. * Add a transform node to the list of scene's transform nodes
  26132. * @param newTransformNode defines the transform node to add
  26133. */
  26134. Scene.prototype.addTransformNode = function (newTransformNode) {
  26135. this.transformNodes.push(newTransformNode);
  26136. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26137. };
  26138. /**
  26139. * Remove a transform node for the list of scene's transform nodes
  26140. * @param toRemove defines the transform node to remove
  26141. * @returns the index where the transform node was in the transform node list
  26142. */
  26143. Scene.prototype.removeTransformNode = function (toRemove) {
  26144. var index = this.transformNodes.indexOf(toRemove);
  26145. if (index !== -1) {
  26146. // Remove from the scene if found
  26147. this.transformNodes.splice(index, 1);
  26148. }
  26149. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26150. return index;
  26151. };
  26152. /**
  26153. * Remove a skeleton for the list of scene's skeletons
  26154. * @param toRemove defines the skeleton to remove
  26155. * @returns the index where the skeleton was in the skeleton list
  26156. */
  26157. Scene.prototype.removeSkeleton = function (toRemove) {
  26158. var index = this.skeletons.indexOf(toRemove);
  26159. if (index !== -1) {
  26160. // Remove from the scene if found
  26161. this.skeletons.splice(index, 1);
  26162. }
  26163. return index;
  26164. };
  26165. /**
  26166. * Remove a morph target for the list of scene's morph targets
  26167. * @param toRemove defines the morph target to remove
  26168. * @returns the index where the morph target was in the morph target list
  26169. */
  26170. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26171. var index = this.morphTargetManagers.indexOf(toRemove);
  26172. if (index !== -1) {
  26173. // Remove from the scene if found
  26174. this.morphTargetManagers.splice(index, 1);
  26175. }
  26176. return index;
  26177. };
  26178. /**
  26179. * Remove a light for the list of scene's lights
  26180. * @param toRemove defines the light to remove
  26181. * @returns the index where the light was in the light list
  26182. */
  26183. Scene.prototype.removeLight = function (toRemove) {
  26184. var index = this.lights.indexOf(toRemove);
  26185. if (index !== -1) {
  26186. // Remove from meshes
  26187. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26188. var mesh = _a[_i];
  26189. mesh._removeLightSource(toRemove);
  26190. }
  26191. // Remove from the scene if mesh found
  26192. this.lights.splice(index, 1);
  26193. this.sortLightsByPriority();
  26194. }
  26195. this.onLightRemovedObservable.notifyObservers(toRemove);
  26196. return index;
  26197. };
  26198. /**
  26199. * Remove a camera for the list of scene's cameras
  26200. * @param toRemove defines the camera to remove
  26201. * @returns the index where the camera was in the camera list
  26202. */
  26203. Scene.prototype.removeCamera = function (toRemove) {
  26204. var index = this.cameras.indexOf(toRemove);
  26205. if (index !== -1) {
  26206. // Remove from the scene if mesh found
  26207. this.cameras.splice(index, 1);
  26208. }
  26209. // Remove from activeCameras
  26210. var index2 = this.activeCameras.indexOf(toRemove);
  26211. if (index2 !== -1) {
  26212. // Remove from the scene if mesh found
  26213. this.activeCameras.splice(index2, 1);
  26214. }
  26215. // Reset the activeCamera
  26216. if (this.activeCamera === toRemove) {
  26217. if (this.cameras.length > 0) {
  26218. this.activeCamera = this.cameras[0];
  26219. }
  26220. else {
  26221. this.activeCamera = null;
  26222. }
  26223. }
  26224. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26225. return index;
  26226. };
  26227. /**
  26228. * Remove a particle system for the list of scene's particle systems
  26229. * @param toRemove defines the particle system to remove
  26230. * @returns the index where the particle system was in the particle system list
  26231. */
  26232. Scene.prototype.removeParticleSystem = function (toRemove) {
  26233. var index = this.particleSystems.indexOf(toRemove);
  26234. if (index !== -1) {
  26235. this.particleSystems.splice(index, 1);
  26236. }
  26237. return index;
  26238. };
  26239. /**
  26240. * Remove a animation for the list of scene's animations
  26241. * @param toRemove defines the animation to remove
  26242. * @returns the index where the animation was in the animation list
  26243. */
  26244. Scene.prototype.removeAnimation = function (toRemove) {
  26245. var index = this.animations.indexOf(toRemove);
  26246. if (index !== -1) {
  26247. this.animations.splice(index, 1);
  26248. }
  26249. return index;
  26250. };
  26251. /**
  26252. * Removes the given animation group from this scene.
  26253. * @param toRemove The animation group to remove
  26254. * @returns The index of the removed animation group
  26255. */
  26256. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26257. var index = this.animationGroups.indexOf(toRemove);
  26258. if (index !== -1) {
  26259. this.animationGroups.splice(index, 1);
  26260. }
  26261. return index;
  26262. };
  26263. /**
  26264. * Removes the given multi-material from this scene.
  26265. * @param toRemove The multi-material to remove
  26266. * @returns The index of the removed multi-material
  26267. */
  26268. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26269. var index = this.multiMaterials.indexOf(toRemove);
  26270. if (index !== -1) {
  26271. this.multiMaterials.splice(index, 1);
  26272. }
  26273. return index;
  26274. };
  26275. /**
  26276. * Removes the given material from this scene.
  26277. * @param toRemove The material to remove
  26278. * @returns The index of the removed material
  26279. */
  26280. Scene.prototype.removeMaterial = function (toRemove) {
  26281. var index = this.materials.indexOf(toRemove);
  26282. if (index !== -1) {
  26283. this.materials.splice(index, 1);
  26284. }
  26285. return index;
  26286. };
  26287. /**
  26288. * Removes the given action manager from this scene.
  26289. * @param toRemove The action manager to remove
  26290. * @returns The index of the removed action manager
  26291. */
  26292. Scene.prototype.removeActionManager = function (toRemove) {
  26293. var index = this.actionManagers.indexOf(toRemove);
  26294. if (index !== -1) {
  26295. this.actionManagers.splice(index, 1);
  26296. }
  26297. return index;
  26298. };
  26299. /**
  26300. * Removes the given texture from this scene.
  26301. * @param toRemove The texture to remove
  26302. * @returns The index of the removed texture
  26303. */
  26304. Scene.prototype.removeTexture = function (toRemove) {
  26305. var index = this.textures.indexOf(toRemove);
  26306. if (index !== -1) {
  26307. this.textures.splice(index, 1);
  26308. }
  26309. return index;
  26310. };
  26311. /**
  26312. * Adds the given light to this scene
  26313. * @param newLight The light to add
  26314. */
  26315. Scene.prototype.addLight = function (newLight) {
  26316. this.lights.push(newLight);
  26317. this.sortLightsByPriority();
  26318. // Add light to all meshes (To support if the light is removed and then readded)
  26319. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26320. var mesh = _a[_i];
  26321. if (mesh._lightSources.indexOf(newLight) === -1) {
  26322. mesh._lightSources.push(newLight);
  26323. mesh._resyncLightSources();
  26324. }
  26325. }
  26326. this.onNewLightAddedObservable.notifyObservers(newLight);
  26327. };
  26328. /**
  26329. * Sorts the list list based on light priorities
  26330. */
  26331. Scene.prototype.sortLightsByPriority = function () {
  26332. if (this.requireLightSorting) {
  26333. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26334. }
  26335. };
  26336. /**
  26337. * Adds the given camera to this scene
  26338. * @param newCamera The camera to add
  26339. */
  26340. Scene.prototype.addCamera = function (newCamera) {
  26341. this.cameras.push(newCamera);
  26342. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26343. };
  26344. /**
  26345. * Adds the given skeleton to this scene
  26346. * @param newSkeleton The skeleton to add
  26347. */
  26348. Scene.prototype.addSkeleton = function (newSkeleton) {
  26349. this.skeletons.push(newSkeleton);
  26350. };
  26351. /**
  26352. * Adds the given particle system to this scene
  26353. * @param newParticleSystem The particle system to add
  26354. */
  26355. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26356. this.particleSystems.push(newParticleSystem);
  26357. };
  26358. /**
  26359. * Adds the given animation to this scene
  26360. * @param newAnimation The animation to add
  26361. */
  26362. Scene.prototype.addAnimation = function (newAnimation) {
  26363. this.animations.push(newAnimation);
  26364. };
  26365. /**
  26366. * Adds the given animation group to this scene.
  26367. * @param newAnimationGroup The animation group to add
  26368. */
  26369. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26370. this.animationGroups.push(newAnimationGroup);
  26371. };
  26372. /**
  26373. * Adds the given multi-material to this scene
  26374. * @param newMultiMaterial The multi-material to add
  26375. */
  26376. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26377. this.multiMaterials.push(newMultiMaterial);
  26378. };
  26379. /**
  26380. * Adds the given material to this scene
  26381. * @param newMaterial The material to add
  26382. */
  26383. Scene.prototype.addMaterial = function (newMaterial) {
  26384. this.materials.push(newMaterial);
  26385. };
  26386. /**
  26387. * Adds the given morph target to this scene
  26388. * @param newMorphTargetManager The morph target to add
  26389. */
  26390. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26391. this.morphTargetManagers.push(newMorphTargetManager);
  26392. };
  26393. /**
  26394. * Adds the given geometry to this scene
  26395. * @param newGeometry The geometry to add
  26396. */
  26397. Scene.prototype.addGeometry = function (newGeometry) {
  26398. this.geometries.push(newGeometry);
  26399. };
  26400. /**
  26401. * Adds the given action manager to this scene
  26402. * @param newActionManager The action manager to add
  26403. */
  26404. Scene.prototype.addActionManager = function (newActionManager) {
  26405. this.actionManagers.push(newActionManager);
  26406. };
  26407. /**
  26408. * Adds the given texture to this scene.
  26409. * @param newTexture The texture to add
  26410. */
  26411. Scene.prototype.addTexture = function (newTexture) {
  26412. this.textures.push(newTexture);
  26413. };
  26414. /**
  26415. * Switch active camera
  26416. * @param newCamera defines the new active camera
  26417. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26418. */
  26419. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26420. if (attachControl === void 0) { attachControl = true; }
  26421. var canvas = this._engine.getRenderingCanvas();
  26422. if (!canvas) {
  26423. return;
  26424. }
  26425. if (this.activeCamera) {
  26426. this.activeCamera.detachControl(canvas);
  26427. }
  26428. this.activeCamera = newCamera;
  26429. if (attachControl) {
  26430. newCamera.attachControl(canvas);
  26431. }
  26432. };
  26433. /**
  26434. * sets the active camera of the scene using its ID
  26435. * @param id defines the camera's ID
  26436. * @return the new active camera or null if none found.
  26437. */
  26438. Scene.prototype.setActiveCameraByID = function (id) {
  26439. var camera = this.getCameraByID(id);
  26440. if (camera) {
  26441. this.activeCamera = camera;
  26442. return camera;
  26443. }
  26444. return null;
  26445. };
  26446. /**
  26447. * sets the active camera of the scene using its name
  26448. * @param name defines the camera's name
  26449. * @returns the new active camera or null if none found.
  26450. */
  26451. Scene.prototype.setActiveCameraByName = function (name) {
  26452. var camera = this.getCameraByName(name);
  26453. if (camera) {
  26454. this.activeCamera = camera;
  26455. return camera;
  26456. }
  26457. return null;
  26458. };
  26459. /**
  26460. * get an animation group using its name
  26461. * @param name defines the material's name
  26462. * @return the animation group or null if none found.
  26463. */
  26464. Scene.prototype.getAnimationGroupByName = function (name) {
  26465. for (var index = 0; index < this.animationGroups.length; index++) {
  26466. if (this.animationGroups[index].name === name) {
  26467. return this.animationGroups[index];
  26468. }
  26469. }
  26470. return null;
  26471. };
  26472. /**
  26473. * get a material using its id
  26474. * @param id defines the material's ID
  26475. * @return the material or null if none found.
  26476. */
  26477. Scene.prototype.getMaterialByID = function (id) {
  26478. for (var index = 0; index < this.materials.length; index++) {
  26479. if (this.materials[index].id === id) {
  26480. return this.materials[index];
  26481. }
  26482. }
  26483. return null;
  26484. };
  26485. /**
  26486. * Gets a material using its name
  26487. * @param name defines the material's name
  26488. * @return the material or null if none found.
  26489. */
  26490. Scene.prototype.getMaterialByName = function (name) {
  26491. for (var index = 0; index < this.materials.length; index++) {
  26492. if (this.materials[index].name === name) {
  26493. return this.materials[index];
  26494. }
  26495. }
  26496. return null;
  26497. };
  26498. /**
  26499. * Gets a camera using its id
  26500. * @param id defines the id to look for
  26501. * @returns the camera or null if not found
  26502. */
  26503. Scene.prototype.getCameraByID = function (id) {
  26504. for (var index = 0; index < this.cameras.length; index++) {
  26505. if (this.cameras[index].id === id) {
  26506. return this.cameras[index];
  26507. }
  26508. }
  26509. return null;
  26510. };
  26511. /**
  26512. * Gets a camera using its unique id
  26513. * @param uniqueId defines the unique id to look for
  26514. * @returns the camera or null if not found
  26515. */
  26516. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26517. for (var index = 0; index < this.cameras.length; index++) {
  26518. if (this.cameras[index].uniqueId === uniqueId) {
  26519. return this.cameras[index];
  26520. }
  26521. }
  26522. return null;
  26523. };
  26524. /**
  26525. * Gets a camera using its name
  26526. * @param name defines the camera's name
  26527. * @return the camera or null if none found.
  26528. */
  26529. Scene.prototype.getCameraByName = function (name) {
  26530. for (var index = 0; index < this.cameras.length; index++) {
  26531. if (this.cameras[index].name === name) {
  26532. return this.cameras[index];
  26533. }
  26534. }
  26535. return null;
  26536. };
  26537. /**
  26538. * Gets a bone using its id
  26539. * @param id defines the bone's id
  26540. * @return the bone or null if not found
  26541. */
  26542. Scene.prototype.getBoneByID = function (id) {
  26543. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26544. var skeleton = this.skeletons[skeletonIndex];
  26545. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26546. if (skeleton.bones[boneIndex].id === id) {
  26547. return skeleton.bones[boneIndex];
  26548. }
  26549. }
  26550. }
  26551. return null;
  26552. };
  26553. /**
  26554. * Gets a bone using its id
  26555. * @param name defines the bone's name
  26556. * @return the bone or null if not found
  26557. */
  26558. Scene.prototype.getBoneByName = function (name) {
  26559. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26560. var skeleton = this.skeletons[skeletonIndex];
  26561. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26562. if (skeleton.bones[boneIndex].name === name) {
  26563. return skeleton.bones[boneIndex];
  26564. }
  26565. }
  26566. }
  26567. return null;
  26568. };
  26569. /**
  26570. * Gets a light node using its name
  26571. * @param name defines the the light's name
  26572. * @return the light or null if none found.
  26573. */
  26574. Scene.prototype.getLightByName = function (name) {
  26575. for (var index = 0; index < this.lights.length; index++) {
  26576. if (this.lights[index].name === name) {
  26577. return this.lights[index];
  26578. }
  26579. }
  26580. return null;
  26581. };
  26582. /**
  26583. * Gets a light node using its id
  26584. * @param id defines the light's id
  26585. * @return the light or null if none found.
  26586. */
  26587. Scene.prototype.getLightByID = function (id) {
  26588. for (var index = 0; index < this.lights.length; index++) {
  26589. if (this.lights[index].id === id) {
  26590. return this.lights[index];
  26591. }
  26592. }
  26593. return null;
  26594. };
  26595. /**
  26596. * Gets a light node using its scene-generated unique ID
  26597. * @param uniqueId defines the light's unique id
  26598. * @return the light or null if none found.
  26599. */
  26600. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26601. for (var index = 0; index < this.lights.length; index++) {
  26602. if (this.lights[index].uniqueId === uniqueId) {
  26603. return this.lights[index];
  26604. }
  26605. }
  26606. return null;
  26607. };
  26608. /**
  26609. * Gets a particle system by id
  26610. * @param id defines the particle system id
  26611. * @return the corresponding system or null if none found
  26612. */
  26613. Scene.prototype.getParticleSystemByID = function (id) {
  26614. for (var index = 0; index < this.particleSystems.length; index++) {
  26615. if (this.particleSystems[index].id === id) {
  26616. return this.particleSystems[index];
  26617. }
  26618. }
  26619. return null;
  26620. };
  26621. /**
  26622. * Gets a geometry using its ID
  26623. * @param id defines the geometry's id
  26624. * @return the geometry or null if none found.
  26625. */
  26626. Scene.prototype.getGeometryByID = function (id) {
  26627. for (var index = 0; index < this.geometries.length; index++) {
  26628. if (this.geometries[index].id === id) {
  26629. return this.geometries[index];
  26630. }
  26631. }
  26632. return null;
  26633. };
  26634. /**
  26635. * Add a new geometry to this scene
  26636. * @param geometry defines the geometry to be added to the scene.
  26637. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26638. * @return a boolean defining if the geometry was added or not
  26639. */
  26640. Scene.prototype.pushGeometry = function (geometry, force) {
  26641. if (!force && this.getGeometryByID(geometry.id)) {
  26642. return false;
  26643. }
  26644. this.geometries.push(geometry);
  26645. //notify the collision coordinator
  26646. if (this.collisionCoordinator) {
  26647. this.collisionCoordinator.onGeometryAdded(geometry);
  26648. }
  26649. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26650. return true;
  26651. };
  26652. /**
  26653. * Removes an existing geometry
  26654. * @param geometry defines the geometry to be removed from the scene
  26655. * @return a boolean defining if the geometry was removed or not
  26656. */
  26657. Scene.prototype.removeGeometry = function (geometry) {
  26658. var index = this.geometries.indexOf(geometry);
  26659. if (index > -1) {
  26660. this.geometries.splice(index, 1);
  26661. //notify the collision coordinator
  26662. if (this.collisionCoordinator) {
  26663. this.collisionCoordinator.onGeometryDeleted(geometry);
  26664. }
  26665. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26666. return true;
  26667. }
  26668. return false;
  26669. };
  26670. /**
  26671. * Gets the list of geometries attached to the scene
  26672. * @returns an array of Geometry
  26673. */
  26674. Scene.prototype.getGeometries = function () {
  26675. return this.geometries;
  26676. };
  26677. /**
  26678. * Gets the first added mesh found of a given ID
  26679. * @param id defines the id to search for
  26680. * @return the mesh found or null if not found at all
  26681. */
  26682. Scene.prototype.getMeshByID = function (id) {
  26683. for (var index = 0; index < this.meshes.length; index++) {
  26684. if (this.meshes[index].id === id) {
  26685. return this.meshes[index];
  26686. }
  26687. }
  26688. return null;
  26689. };
  26690. /**
  26691. * Gets a list of meshes using their id
  26692. * @param id defines the id to search for
  26693. * @returns a list of meshes
  26694. */
  26695. Scene.prototype.getMeshesByID = function (id) {
  26696. return this.meshes.filter(function (m) {
  26697. return m.id === id;
  26698. });
  26699. };
  26700. /**
  26701. * Gets the first added transform node found of a given ID
  26702. * @param id defines the id to search for
  26703. * @return the found transform node or null if not found at all.
  26704. */
  26705. Scene.prototype.getTransformNodeByID = function (id) {
  26706. for (var index = 0; index < this.transformNodes.length; index++) {
  26707. if (this.transformNodes[index].id === id) {
  26708. return this.transformNodes[index];
  26709. }
  26710. }
  26711. return null;
  26712. };
  26713. /**
  26714. * Gets a list of transform nodes using their id
  26715. * @param id defines the id to search for
  26716. * @returns a list of transform nodes
  26717. */
  26718. Scene.prototype.getTransformNodesByID = function (id) {
  26719. return this.transformNodes.filter(function (m) {
  26720. return m.id === id;
  26721. });
  26722. };
  26723. /**
  26724. * Gets a mesh with its auto-generated unique id
  26725. * @param uniqueId defines the unique id to search for
  26726. * @return the found mesh or null if not found at all.
  26727. */
  26728. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26729. for (var index = 0; index < this.meshes.length; index++) {
  26730. if (this.meshes[index].uniqueId === uniqueId) {
  26731. return this.meshes[index];
  26732. }
  26733. }
  26734. return null;
  26735. };
  26736. /**
  26737. * Gets a the last added mesh using a given id
  26738. * @param id defines the id to search for
  26739. * @return the found mesh or null if not found at all.
  26740. */
  26741. Scene.prototype.getLastMeshByID = function (id) {
  26742. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26743. if (this.meshes[index].id === id) {
  26744. return this.meshes[index];
  26745. }
  26746. }
  26747. return null;
  26748. };
  26749. /**
  26750. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26751. * @param id defines the id to search for
  26752. * @return the found node or null if not found at all
  26753. */
  26754. Scene.prototype.getLastEntryByID = function (id) {
  26755. var index;
  26756. for (index = this.meshes.length - 1; index >= 0; index--) {
  26757. if (this.meshes[index].id === id) {
  26758. return this.meshes[index];
  26759. }
  26760. }
  26761. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26762. if (this.transformNodes[index].id === id) {
  26763. return this.transformNodes[index];
  26764. }
  26765. }
  26766. for (index = this.cameras.length - 1; index >= 0; index--) {
  26767. if (this.cameras[index].id === id) {
  26768. return this.cameras[index];
  26769. }
  26770. }
  26771. for (index = this.lights.length - 1; index >= 0; index--) {
  26772. if (this.lights[index].id === id) {
  26773. return this.lights[index];
  26774. }
  26775. }
  26776. return null;
  26777. };
  26778. /**
  26779. * Gets a node (Mesh, Camera, Light) using a given id
  26780. * @param id defines the id to search for
  26781. * @return the found node or null if not found at all
  26782. */
  26783. Scene.prototype.getNodeByID = function (id) {
  26784. var mesh = this.getMeshByID(id);
  26785. if (mesh) {
  26786. return mesh;
  26787. }
  26788. var light = this.getLightByID(id);
  26789. if (light) {
  26790. return light;
  26791. }
  26792. var camera = this.getCameraByID(id);
  26793. if (camera) {
  26794. return camera;
  26795. }
  26796. var bone = this.getBoneByID(id);
  26797. return bone;
  26798. };
  26799. /**
  26800. * Gets a node (Mesh, Camera, Light) using a given name
  26801. * @param name defines the name to search for
  26802. * @return the found node or null if not found at all.
  26803. */
  26804. Scene.prototype.getNodeByName = function (name) {
  26805. var mesh = this.getMeshByName(name);
  26806. if (mesh) {
  26807. return mesh;
  26808. }
  26809. var light = this.getLightByName(name);
  26810. if (light) {
  26811. return light;
  26812. }
  26813. var camera = this.getCameraByName(name);
  26814. if (camera) {
  26815. return camera;
  26816. }
  26817. var bone = this.getBoneByName(name);
  26818. return bone;
  26819. };
  26820. /**
  26821. * Gets a mesh using a given name
  26822. * @param name defines the name to search for
  26823. * @return the found mesh or null if not found at all.
  26824. */
  26825. Scene.prototype.getMeshByName = function (name) {
  26826. for (var index = 0; index < this.meshes.length; index++) {
  26827. if (this.meshes[index].name === name) {
  26828. return this.meshes[index];
  26829. }
  26830. }
  26831. return null;
  26832. };
  26833. /**
  26834. * Gets a transform node using a given name
  26835. * @param name defines the name to search for
  26836. * @return the found transform node or null if not found at all.
  26837. */
  26838. Scene.prototype.getTransformNodeByName = function (name) {
  26839. for (var index = 0; index < this.transformNodes.length; index++) {
  26840. if (this.transformNodes[index].name === name) {
  26841. return this.transformNodes[index];
  26842. }
  26843. }
  26844. return null;
  26845. };
  26846. /**
  26847. * Gets a sound using a given name
  26848. * @param name defines the name to search for
  26849. * @return the found sound or null if not found at all.
  26850. */
  26851. Scene.prototype.getSoundByName = function (name) {
  26852. var index;
  26853. if (BABYLON.AudioEngine) {
  26854. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26855. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26856. return this.mainSoundTrack.soundCollection[index];
  26857. }
  26858. }
  26859. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26860. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26861. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26862. return this.soundTracks[sdIndex].soundCollection[index];
  26863. }
  26864. }
  26865. }
  26866. }
  26867. return null;
  26868. };
  26869. /**
  26870. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26871. * @param id defines the id to search for
  26872. * @return the found skeleton or null if not found at all.
  26873. */
  26874. Scene.prototype.getLastSkeletonByID = function (id) {
  26875. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26876. if (this.skeletons[index].id === id) {
  26877. return this.skeletons[index];
  26878. }
  26879. }
  26880. return null;
  26881. };
  26882. /**
  26883. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26884. * @param id defines the id to search for
  26885. * @return the found skeleton or null if not found at all.
  26886. */
  26887. Scene.prototype.getSkeletonById = function (id) {
  26888. for (var index = 0; index < this.skeletons.length; index++) {
  26889. if (this.skeletons[index].id === id) {
  26890. return this.skeletons[index];
  26891. }
  26892. }
  26893. return null;
  26894. };
  26895. /**
  26896. * Gets a skeleton using a given name
  26897. * @param name defines the name to search for
  26898. * @return the found skeleton or null if not found at all.
  26899. */
  26900. Scene.prototype.getSkeletonByName = function (name) {
  26901. for (var index = 0; index < this.skeletons.length; index++) {
  26902. if (this.skeletons[index].name === name) {
  26903. return this.skeletons[index];
  26904. }
  26905. }
  26906. return null;
  26907. };
  26908. /**
  26909. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26910. * @param id defines the id to search for
  26911. * @return the found morph target manager or null if not found at all.
  26912. */
  26913. Scene.prototype.getMorphTargetManagerById = function (id) {
  26914. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26915. if (this.morphTargetManagers[index].uniqueId === id) {
  26916. return this.morphTargetManagers[index];
  26917. }
  26918. }
  26919. return null;
  26920. };
  26921. /**
  26922. * Gets a boolean indicating if the given mesh is active
  26923. * @param mesh defines the mesh to look for
  26924. * @returns true if the mesh is in the active list
  26925. */
  26926. Scene.prototype.isActiveMesh = function (mesh) {
  26927. return (this._activeMeshes.indexOf(mesh) !== -1);
  26928. };
  26929. Object.defineProperty(Scene.prototype, "uid", {
  26930. /**
  26931. * Return a unique id as a string which can serve as an identifier for the scene
  26932. */
  26933. get: function () {
  26934. if (!this._uid) {
  26935. this._uid = BABYLON.Tools.RandomId();
  26936. }
  26937. return this._uid;
  26938. },
  26939. enumerable: true,
  26940. configurable: true
  26941. });
  26942. /**
  26943. * Add an externaly attached data from its key.
  26944. * This method call will fail and return false, if such key already exists.
  26945. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26946. * @param key the unique key that identifies the data
  26947. * @param data the data object to associate to the key for this Engine instance
  26948. * @return true if no such key were already present and the data was added successfully, false otherwise
  26949. */
  26950. Scene.prototype.addExternalData = function (key, data) {
  26951. if (!this._externalData) {
  26952. this._externalData = new BABYLON.StringDictionary();
  26953. }
  26954. return this._externalData.add(key, data);
  26955. };
  26956. /**
  26957. * Get an externaly attached data from its key
  26958. * @param key the unique key that identifies the data
  26959. * @return the associated data, if present (can be null), or undefined if not present
  26960. */
  26961. Scene.prototype.getExternalData = function (key) {
  26962. if (!this._externalData) {
  26963. return null;
  26964. }
  26965. return this._externalData.get(key);
  26966. };
  26967. /**
  26968. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26969. * @param key the unique key that identifies the data
  26970. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26971. * @return the associated data, can be null if the factory returned null.
  26972. */
  26973. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26974. if (!this._externalData) {
  26975. this._externalData = new BABYLON.StringDictionary();
  26976. }
  26977. return this._externalData.getOrAddWithFactory(key, factory);
  26978. };
  26979. /**
  26980. * Remove an externaly attached data from the Engine instance
  26981. * @param key the unique key that identifies the data
  26982. * @return true if the data was successfully removed, false if it doesn't exist
  26983. */
  26984. Scene.prototype.removeExternalData = function (key) {
  26985. return this._externalData.remove(key);
  26986. };
  26987. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26988. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26989. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  26990. var step = _a[_i];
  26991. step.action(mesh, subMesh);
  26992. }
  26993. var material = subMesh.getMaterial();
  26994. if (material !== null && material !== undefined) {
  26995. // Render targets
  26996. if (material.getRenderTargetTextures !== undefined) {
  26997. if (this._processedMaterials.indexOf(material) === -1) {
  26998. this._processedMaterials.push(material);
  26999. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27000. }
  27001. }
  27002. // Dispatch
  27003. this._activeIndices.addCount(subMesh.indexCount, false);
  27004. this._renderingManager.dispatch(subMesh, mesh, material);
  27005. }
  27006. }
  27007. };
  27008. /**
  27009. * Clear the processed materials smart array preventing retention point in material dispose.
  27010. */
  27011. Scene.prototype.freeProcessedMaterials = function () {
  27012. this._processedMaterials.dispose();
  27013. };
  27014. /**
  27015. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27016. */
  27017. Scene.prototype.freeActiveMeshes = function () {
  27018. this._activeMeshes.dispose();
  27019. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27020. this.activeCamera._activeMeshes.dispose();
  27021. }
  27022. if (this.activeCameras) {
  27023. for (var i = 0; i < this.activeCameras.length; i++) {
  27024. var activeCamera = this.activeCameras[i];
  27025. if (activeCamera && activeCamera._activeMeshes) {
  27026. activeCamera._activeMeshes.dispose();
  27027. }
  27028. }
  27029. }
  27030. };
  27031. /**
  27032. * Clear the info related to rendering groups preventing retention points during dispose.
  27033. */
  27034. Scene.prototype.freeRenderingGroups = function () {
  27035. if (this._renderingManager) {
  27036. this._renderingManager.freeRenderingGroups();
  27037. }
  27038. if (this.textures) {
  27039. for (var i = 0; i < this.textures.length; i++) {
  27040. var texture = this.textures[i];
  27041. if (texture && texture.renderList) {
  27042. texture.freeRenderingGroups();
  27043. }
  27044. }
  27045. }
  27046. };
  27047. /** @hidden */
  27048. Scene.prototype._isInIntermediateRendering = function () {
  27049. return this._intermediateRendering;
  27050. };
  27051. /**
  27052. * Defines the current active mesh candidate provider
  27053. * @param provider defines the provider to use
  27054. */
  27055. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27056. this._activeMeshCandidateProvider = provider;
  27057. };
  27058. /**
  27059. * Gets the current active mesh candidate provider
  27060. * @returns the current active mesh candidate provider
  27061. */
  27062. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27063. return this._activeMeshCandidateProvider;
  27064. };
  27065. /**
  27066. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27067. * @returns the current scene
  27068. */
  27069. Scene.prototype.freezeActiveMeshes = function () {
  27070. if (!this.activeCamera) {
  27071. return this;
  27072. }
  27073. if (!this._frustumPlanes) {
  27074. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27075. }
  27076. this._evaluateActiveMeshes();
  27077. this._activeMeshesFrozen = true;
  27078. return this;
  27079. };
  27080. /**
  27081. * Use this function to restart evaluating active meshes on every frame
  27082. * @returns the current scene
  27083. */
  27084. Scene.prototype.unfreezeActiveMeshes = function () {
  27085. this._activeMeshesFrozen = false;
  27086. return this;
  27087. };
  27088. Scene.prototype._evaluateActiveMeshes = function () {
  27089. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27090. return;
  27091. }
  27092. if (!this.activeCamera) {
  27093. return;
  27094. }
  27095. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27096. this.activeCamera._activeMeshes.reset();
  27097. this._activeMeshes.reset();
  27098. this._renderingManager.reset();
  27099. this._processedMaterials.reset();
  27100. this._activeParticleSystems.reset();
  27101. this._activeSkeletons.reset();
  27102. this._softwareSkinnedMeshes.reset();
  27103. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27104. var step = _a[_i];
  27105. step.action();
  27106. }
  27107. // Meshes
  27108. var meshes;
  27109. var len;
  27110. var checkIsEnabled = true;
  27111. // Determine mesh candidates
  27112. if (this._activeMeshCandidateProvider !== undefined) {
  27113. // Use _activeMeshCandidateProvider
  27114. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27115. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27116. if (meshes !== undefined) {
  27117. len = meshes.length;
  27118. }
  27119. else {
  27120. len = 0;
  27121. }
  27122. }
  27123. else if (this._selectionOctree !== undefined) {
  27124. // Octree
  27125. var selection = this._selectionOctree.select(this._frustumPlanes);
  27126. meshes = selection.data;
  27127. len = selection.length;
  27128. }
  27129. else {
  27130. // Full scene traversal
  27131. len = this.meshes.length;
  27132. meshes = this.meshes;
  27133. }
  27134. // Check each mesh
  27135. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27136. mesh = meshes[meshIndex];
  27137. if (mesh.isBlocked) {
  27138. continue;
  27139. }
  27140. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27141. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27142. continue;
  27143. }
  27144. mesh.computeWorldMatrix();
  27145. // Intersections
  27146. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27147. this._meshesForIntersections.pushNoDuplicate(mesh);
  27148. }
  27149. // Switch to current LOD
  27150. meshLOD = mesh.getLOD(this.activeCamera);
  27151. if (meshLOD === undefined || meshLOD === null) {
  27152. continue;
  27153. }
  27154. mesh._preActivate();
  27155. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27156. this._activeMeshes.push(mesh);
  27157. this.activeCamera._activeMeshes.push(mesh);
  27158. mesh._activate(this._renderId);
  27159. if (meshLOD !== mesh) {
  27160. meshLOD._activate(this._renderId);
  27161. }
  27162. this._activeMesh(mesh, meshLOD);
  27163. }
  27164. }
  27165. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27166. // Particle systems
  27167. if (this.particlesEnabled) {
  27168. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27169. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27170. var particleSystem = this.particleSystems[particleIndex];
  27171. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27172. continue;
  27173. }
  27174. var emitter = particleSystem.emitter;
  27175. if (!emitter.position || emitter.isEnabled()) {
  27176. this._activeParticleSystems.push(particleSystem);
  27177. particleSystem.animate();
  27178. this._renderingManager.dispatchParticles(particleSystem);
  27179. }
  27180. }
  27181. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27182. }
  27183. };
  27184. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27185. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27186. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27187. mesh.skeleton.prepare();
  27188. }
  27189. if (!mesh.computeBonesUsingShaders) {
  27190. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27191. }
  27192. }
  27193. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27194. var step = _a[_i];
  27195. step.action(sourceMesh, mesh);
  27196. }
  27197. if (mesh !== undefined && mesh !== null
  27198. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27199. // Submeshes Octrees
  27200. var len;
  27201. var subMeshes;
  27202. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27203. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27204. len = intersections.length;
  27205. subMeshes = intersections.data;
  27206. }
  27207. else {
  27208. subMeshes = mesh.subMeshes;
  27209. len = subMeshes.length;
  27210. }
  27211. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27212. subMesh = subMeshes[subIndex];
  27213. this._evaluateSubMesh(subMesh, mesh);
  27214. }
  27215. }
  27216. };
  27217. /**
  27218. * Update the transform matrix to update from the current active camera
  27219. * @param force defines a boolean used to force the update even if cache is up to date
  27220. */
  27221. Scene.prototype.updateTransformMatrix = function (force) {
  27222. if (!this.activeCamera) {
  27223. return;
  27224. }
  27225. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27226. };
  27227. /**
  27228. * 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)
  27229. * @param alternateCamera defines the camera to use
  27230. */
  27231. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27232. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27233. };
  27234. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27235. if (camera && camera._skipRendering) {
  27236. return;
  27237. }
  27238. var engine = this._engine;
  27239. this.activeCamera = camera;
  27240. if (!this.activeCamera)
  27241. throw new Error("Active camera not set");
  27242. // Viewport
  27243. engine.setViewport(this.activeCamera.viewport);
  27244. // Camera
  27245. this.resetCachedMaterial();
  27246. this._renderId++;
  27247. this.updateTransformMatrix();
  27248. if (camera._alternateCamera) {
  27249. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27250. this._alternateRendering = true;
  27251. }
  27252. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27253. // Meshes
  27254. this._evaluateActiveMeshes();
  27255. // Software skinning
  27256. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27257. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27258. mesh.applySkeleton(mesh.skeleton);
  27259. }
  27260. // Render targets
  27261. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27262. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27263. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27264. }
  27265. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27266. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27267. }
  27268. if (this.renderTargetsEnabled) {
  27269. this._intermediateRendering = true;
  27270. if (this._renderTargets.length > 0) {
  27271. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27272. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27273. var renderTarget = this._renderTargets.data[renderIndex];
  27274. if (renderTarget._shouldRender()) {
  27275. this._renderId++;
  27276. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27277. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27278. }
  27279. }
  27280. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27281. this._renderId++;
  27282. }
  27283. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27284. var step = _a[_i];
  27285. step.action(this.activeCamera);
  27286. }
  27287. this._intermediateRendering = false;
  27288. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27289. }
  27290. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27291. // Prepare Frame
  27292. if (this.postProcessManager) {
  27293. this.postProcessManager._prepareFrame();
  27294. }
  27295. // Before Camera Draw
  27296. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27297. var step = _c[_b];
  27298. step.action(this.activeCamera);
  27299. }
  27300. // Render
  27301. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27302. this._renderingManager.render(null, null, true, true);
  27303. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27304. // After Camera Draw
  27305. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27306. var step = _e[_d];
  27307. step.action(this.activeCamera);
  27308. }
  27309. // Finalize frame
  27310. if (this.postProcessManager) {
  27311. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27312. }
  27313. // Reset some special arrays
  27314. this._renderTargets.reset();
  27315. this._alternateRendering = false;
  27316. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27317. };
  27318. Scene.prototype._processSubCameras = function (camera) {
  27319. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27320. this._renderForCamera(camera);
  27321. return;
  27322. }
  27323. // rig cameras
  27324. for (var index = 0; index < camera._rigCameras.length; index++) {
  27325. this._renderForCamera(camera._rigCameras[index], camera);
  27326. }
  27327. this.activeCamera = camera;
  27328. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27329. };
  27330. Scene.prototype._checkIntersections = function () {
  27331. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27332. var sourceMesh = this._meshesForIntersections.data[index];
  27333. if (!sourceMesh.actionManager) {
  27334. continue;
  27335. }
  27336. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27337. var action = sourceMesh.actionManager.actions[actionIndex];
  27338. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27339. var parameters = action.getTriggerParameter();
  27340. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27341. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27342. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27343. if (areIntersecting && currentIntersectionInProgress === -1) {
  27344. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27345. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27346. sourceMesh._intersectionsInProgress.push(otherMesh);
  27347. }
  27348. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27349. sourceMesh._intersectionsInProgress.push(otherMesh);
  27350. }
  27351. }
  27352. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27353. //They intersected, and now they don't.
  27354. //is this trigger an exit trigger? execute an event.
  27355. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27356. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27357. }
  27358. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27359. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27360. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27361. return otherMesh === parameterMesh;
  27362. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27363. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27364. }
  27365. }
  27366. }
  27367. }
  27368. }
  27369. };
  27370. /**
  27371. * Render the scene
  27372. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27373. */
  27374. Scene.prototype.render = function (updateCameras) {
  27375. if (updateCameras === void 0) { updateCameras = true; }
  27376. if (this.isDisposed) {
  27377. return;
  27378. }
  27379. // Register components that have been associated lately to the scene.
  27380. this._registerTransientComponents();
  27381. this._activeParticles.fetchNewFrame();
  27382. this._totalVertices.fetchNewFrame();
  27383. this._activeIndices.fetchNewFrame();
  27384. this._activeBones.fetchNewFrame();
  27385. this._meshesForIntersections.reset();
  27386. this.resetCachedMaterial();
  27387. this.onBeforeAnimationsObservable.notifyObservers(this);
  27388. // Actions
  27389. if (this.actionManager) {
  27390. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27391. }
  27392. //Simplification Queue
  27393. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27394. this.simplificationQueue.executeNext();
  27395. }
  27396. if (this._engine.isDeterministicLockStep()) {
  27397. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27398. var defaultFPS = (60.0 / 1000.0);
  27399. var defaultFrameTime = 1000 / 60; // frame time in MS
  27400. if (this._physicsEngine) {
  27401. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27402. }
  27403. var stepsTaken = 0;
  27404. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27405. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27406. internalSteps = Math.min(internalSteps, maxSubSteps);
  27407. do {
  27408. this.onBeforeStepObservable.notifyObservers(this);
  27409. // Animations
  27410. this._animationRatio = defaultFrameTime * defaultFPS;
  27411. this._animate();
  27412. this.onAfterAnimationsObservable.notifyObservers(this);
  27413. // Physics
  27414. if (this._physicsEngine) {
  27415. this.onBeforePhysicsObservable.notifyObservers(this);
  27416. this._physicsEngine._step(defaultFrameTime / 1000);
  27417. this.onAfterPhysicsObservable.notifyObservers(this);
  27418. }
  27419. this.onAfterStepObservable.notifyObservers(this);
  27420. this._currentStepId++;
  27421. stepsTaken++;
  27422. deltaTime -= defaultFrameTime;
  27423. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27424. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27425. }
  27426. else {
  27427. // Animations
  27428. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27429. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27430. this._animate();
  27431. this.onAfterAnimationsObservable.notifyObservers(this);
  27432. // Physics
  27433. if (this._physicsEngine) {
  27434. this.onBeforePhysicsObservable.notifyObservers(this);
  27435. this._physicsEngine._step(deltaTime / 1000.0);
  27436. this.onAfterPhysicsObservable.notifyObservers(this);
  27437. }
  27438. }
  27439. // Before camera update steps
  27440. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27441. var step = _a[_i];
  27442. step.action();
  27443. }
  27444. // Update Cameras
  27445. if (updateCameras) {
  27446. if (this.activeCameras.length > 0) {
  27447. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27448. var camera = this.activeCameras[cameraIndex];
  27449. camera.update();
  27450. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27451. // rig cameras
  27452. for (var index = 0; index < camera._rigCameras.length; index++) {
  27453. camera._rigCameras[index].update();
  27454. }
  27455. }
  27456. }
  27457. }
  27458. else if (this.activeCamera) {
  27459. this.activeCamera.update();
  27460. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27461. // rig cameras
  27462. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27463. this.activeCamera._rigCameras[index].update();
  27464. }
  27465. }
  27466. }
  27467. }
  27468. // Before render
  27469. this.onBeforeRenderObservable.notifyObservers(this);
  27470. // Customs render targets
  27471. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27472. var engine = this.getEngine();
  27473. var currentActiveCamera = this.activeCamera;
  27474. if (this.renderTargetsEnabled) {
  27475. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27476. this._intermediateRendering = true;
  27477. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27478. var renderTarget = this.customRenderTargets[customIndex];
  27479. if (renderTarget._shouldRender()) {
  27480. this._renderId++;
  27481. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27482. if (!this.activeCamera)
  27483. throw new Error("Active camera not set");
  27484. // Viewport
  27485. engine.setViewport(this.activeCamera.viewport);
  27486. // Camera
  27487. this.updateTransformMatrix();
  27488. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27489. }
  27490. }
  27491. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27492. this._intermediateRendering = false;
  27493. this._renderId++;
  27494. }
  27495. // Restore back buffer
  27496. if (this.customRenderTargets.length > 0) {
  27497. engine.restoreDefaultFramebuffer();
  27498. }
  27499. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27500. this.activeCamera = currentActiveCamera;
  27501. // Procedural textures
  27502. if (this.proceduralTexturesEnabled) {
  27503. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27504. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27505. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27506. if (proceduralTexture._shouldRender()) {
  27507. proceduralTexture.render();
  27508. }
  27509. }
  27510. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27511. }
  27512. // Clear
  27513. if (this.autoClearDepthAndStencil || this.autoClear) {
  27514. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27515. }
  27516. // Shadows
  27517. if (this.shadowsEnabled) {
  27518. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27519. var light = this.lights[lightIndex];
  27520. var shadowGenerator = light.getShadowGenerator();
  27521. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27522. var shadowMap = (shadowGenerator.getShadowMap());
  27523. if (this.textures.indexOf(shadowMap) !== -1) {
  27524. this._renderTargets.push(shadowMap);
  27525. }
  27526. }
  27527. }
  27528. }
  27529. // Depth renderer
  27530. for (var key in this._depthRenderer) {
  27531. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27532. }
  27533. // Geometry renderer
  27534. if (this._geometryBufferRenderer) {
  27535. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27536. }
  27537. // RenderPipeline
  27538. if (this._postProcessRenderPipelineManager) {
  27539. this._postProcessRenderPipelineManager.update();
  27540. }
  27541. // Multi-cameras?
  27542. if (this.activeCameras.length > 0) {
  27543. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27544. if (cameraIndex > 0) {
  27545. this._engine.clear(null, false, true, true);
  27546. }
  27547. this._processSubCameras(this.activeCameras[cameraIndex]);
  27548. }
  27549. }
  27550. else {
  27551. if (!this.activeCamera) {
  27552. throw new Error("No camera defined");
  27553. }
  27554. this._processSubCameras(this.activeCamera);
  27555. }
  27556. // Intersection checks
  27557. this._checkIntersections();
  27558. // Update the audio listener attached to the camera
  27559. if (BABYLON.AudioEngine) {
  27560. this._updateAudioParameters();
  27561. }
  27562. // After render
  27563. if (this.afterRender) {
  27564. this.afterRender();
  27565. }
  27566. this.onAfterRenderObservable.notifyObservers(this);
  27567. // Cleaning
  27568. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27569. var data = this._toBeDisposed.data[index];
  27570. if (data) {
  27571. data.dispose();
  27572. }
  27573. this._toBeDisposed[index] = null;
  27574. }
  27575. this._toBeDisposed.reset();
  27576. if (this.dumpNextRenderTargets) {
  27577. this.dumpNextRenderTargets = false;
  27578. }
  27579. this._activeBones.addCount(0, true);
  27580. this._activeIndices.addCount(0, true);
  27581. this._activeParticles.addCount(0, true);
  27582. };
  27583. Scene.prototype._updateAudioParameters = function () {
  27584. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27585. return;
  27586. }
  27587. var listeningCamera;
  27588. var audioEngine = BABYLON.Engine.audioEngine;
  27589. if (this.activeCameras.length > 0) {
  27590. listeningCamera = this.activeCameras[0];
  27591. }
  27592. else {
  27593. listeningCamera = this.activeCamera;
  27594. }
  27595. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27596. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27597. // for VR cameras
  27598. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27599. listeningCamera = listeningCamera.rigCameras[0];
  27600. }
  27601. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27602. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27603. cameraDirection.normalize();
  27604. // To avoid some errors on GearVR
  27605. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27606. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27607. }
  27608. var i;
  27609. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27610. var sound = this.mainSoundTrack.soundCollection[i];
  27611. if (sound.useCustomAttenuation) {
  27612. sound.updateDistanceFromListener();
  27613. }
  27614. }
  27615. for (i = 0; i < this.soundTracks.length; i++) {
  27616. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27617. sound = this.soundTracks[i].soundCollection[j];
  27618. if (sound.useCustomAttenuation) {
  27619. sound.updateDistanceFromListener();
  27620. }
  27621. }
  27622. }
  27623. }
  27624. };
  27625. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27626. // Audio
  27627. /**
  27628. * Gets or sets if audio support is enabled
  27629. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27630. */
  27631. get: function () {
  27632. return this._audioEnabled;
  27633. },
  27634. set: function (value) {
  27635. this._audioEnabled = value;
  27636. if (BABYLON.AudioEngine) {
  27637. if (this._audioEnabled) {
  27638. this._enableAudio();
  27639. }
  27640. else {
  27641. this._disableAudio();
  27642. }
  27643. }
  27644. },
  27645. enumerable: true,
  27646. configurable: true
  27647. });
  27648. Scene.prototype._disableAudio = function () {
  27649. var i;
  27650. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27651. this.mainSoundTrack.soundCollection[i].pause();
  27652. }
  27653. for (i = 0; i < this.soundTracks.length; i++) {
  27654. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27655. this.soundTracks[i].soundCollection[j].pause();
  27656. }
  27657. }
  27658. };
  27659. Scene.prototype._enableAudio = function () {
  27660. var i;
  27661. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27662. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27663. this.mainSoundTrack.soundCollection[i].play();
  27664. }
  27665. }
  27666. for (i = 0; i < this.soundTracks.length; i++) {
  27667. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27668. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27669. this.soundTracks[i].soundCollection[j].play();
  27670. }
  27671. }
  27672. }
  27673. };
  27674. Object.defineProperty(Scene.prototype, "headphone", {
  27675. /**
  27676. * Gets or sets if audio will be output to headphones
  27677. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27678. */
  27679. get: function () {
  27680. return this._headphone;
  27681. },
  27682. set: function (value) {
  27683. this._headphone = value;
  27684. if (BABYLON.AudioEngine) {
  27685. if (this._headphone) {
  27686. this._switchAudioModeForHeadphones();
  27687. }
  27688. else {
  27689. this._switchAudioModeForNormalSpeakers();
  27690. }
  27691. }
  27692. },
  27693. enumerable: true,
  27694. configurable: true
  27695. });
  27696. Scene.prototype._switchAudioModeForHeadphones = function () {
  27697. this.mainSoundTrack.switchPanningModelToHRTF();
  27698. for (var i = 0; i < this.soundTracks.length; i++) {
  27699. this.soundTracks[i].switchPanningModelToHRTF();
  27700. }
  27701. };
  27702. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27703. this.mainSoundTrack.switchPanningModelToEqualPower();
  27704. for (var i = 0; i < this.soundTracks.length; i++) {
  27705. this.soundTracks[i].switchPanningModelToEqualPower();
  27706. }
  27707. };
  27708. /**
  27709. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27710. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27711. * @returns the created depth renderer
  27712. */
  27713. Scene.prototype.enableDepthRenderer = function (camera) {
  27714. camera = camera || this.activeCamera;
  27715. if (!camera) {
  27716. throw "No camera available to enable depth renderer";
  27717. }
  27718. if (!this._depthRenderer[camera.id]) {
  27719. var textureType = 0;
  27720. if (this._engine.getCaps().textureHalfFloatRender) {
  27721. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27722. }
  27723. else if (this._engine.getCaps().textureFloatRender) {
  27724. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27725. }
  27726. else {
  27727. throw "Depth renderer does not support int texture type";
  27728. }
  27729. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27730. }
  27731. return this._depthRenderer[camera.id];
  27732. };
  27733. /**
  27734. * Disables a depth renderer for a given camera
  27735. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27736. */
  27737. Scene.prototype.disableDepthRenderer = function (camera) {
  27738. camera = camera || this.activeCamera;
  27739. if (!camera || !this._depthRenderer[camera.id]) {
  27740. return;
  27741. }
  27742. this._depthRenderer[camera.id].dispose();
  27743. delete this._depthRenderer[camera.id];
  27744. };
  27745. /**
  27746. * Enables a GeometryBufferRender and associates it with the scene
  27747. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27748. * @returns the GeometryBufferRenderer
  27749. */
  27750. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27751. if (ratio === void 0) { ratio = 1; }
  27752. if (this._geometryBufferRenderer) {
  27753. return this._geometryBufferRenderer;
  27754. }
  27755. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27756. if (!this._geometryBufferRenderer.isSupported) {
  27757. this._geometryBufferRenderer = null;
  27758. }
  27759. return this._geometryBufferRenderer;
  27760. };
  27761. /**
  27762. * Disables the GeometryBufferRender associated with the scene
  27763. */
  27764. Scene.prototype.disableGeometryBufferRenderer = function () {
  27765. if (!this._geometryBufferRenderer) {
  27766. return;
  27767. }
  27768. this._geometryBufferRenderer.dispose();
  27769. this._geometryBufferRenderer = null;
  27770. };
  27771. /**
  27772. * Freeze all materials
  27773. * A frozen material will not be updatable but should be faster to render
  27774. */
  27775. Scene.prototype.freezeMaterials = function () {
  27776. for (var i = 0; i < this.materials.length; i++) {
  27777. this.materials[i].freeze();
  27778. }
  27779. };
  27780. /**
  27781. * Unfreeze all materials
  27782. * A frozen material will not be updatable but should be faster to render
  27783. */
  27784. Scene.prototype.unfreezeMaterials = function () {
  27785. for (var i = 0; i < this.materials.length; i++) {
  27786. this.materials[i].unfreeze();
  27787. }
  27788. };
  27789. /**
  27790. * Releases all held ressources
  27791. */
  27792. Scene.prototype.dispose = function () {
  27793. this.beforeRender = null;
  27794. this.afterRender = null;
  27795. this.skeletons = [];
  27796. this.morphTargetManagers = [];
  27797. this._transientComponents = [];
  27798. this._isReadyForMeshStage.clear();
  27799. this._beforeEvaluateActiveMeshStage.clear();
  27800. this._evaluateSubMeshStage.clear();
  27801. this._activeMeshStage.clear();
  27802. this._cameraDrawRenderTargetStage.clear();
  27803. this._beforeCameraDrawStage.clear();
  27804. this._beforeRenderingGroupDrawStage.clear();
  27805. this._afterRenderingGroupDrawStage.clear();
  27806. this._afterCameraDrawStage.clear();
  27807. this._beforeCameraUpdateStage.clear();
  27808. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27809. var component = _a[_i];
  27810. component.dispose();
  27811. }
  27812. this.importedMeshesFiles = new Array();
  27813. this.stopAllAnimations();
  27814. this.resetCachedMaterial();
  27815. for (var key in this._depthRenderer) {
  27816. this._depthRenderer[key].dispose();
  27817. }
  27818. // Smart arrays
  27819. if (this.activeCamera) {
  27820. this.activeCamera._activeMeshes.dispose();
  27821. this.activeCamera = null;
  27822. }
  27823. this._activeMeshes.dispose();
  27824. this._renderingManager.dispose();
  27825. this._processedMaterials.dispose();
  27826. this._activeParticleSystems.dispose();
  27827. this._activeSkeletons.dispose();
  27828. this._softwareSkinnedMeshes.dispose();
  27829. this._renderTargets.dispose();
  27830. this._registeredForLateAnimationBindings.dispose();
  27831. this._meshesForIntersections.dispose();
  27832. this._toBeDisposed.dispose();
  27833. // Abort active requests
  27834. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27835. var request = _c[_b];
  27836. request.abort();
  27837. }
  27838. // Debug layer
  27839. if (this._debugLayer) {
  27840. this._debugLayer.hide();
  27841. }
  27842. // Events
  27843. this.onDisposeObservable.notifyObservers(this);
  27844. this.onDisposeObservable.clear();
  27845. this.onBeforeRenderObservable.clear();
  27846. this.onAfterRenderObservable.clear();
  27847. this.onBeforeRenderTargetsRenderObservable.clear();
  27848. this.onAfterRenderTargetsRenderObservable.clear();
  27849. this.onAfterStepObservable.clear();
  27850. this.onBeforeStepObservable.clear();
  27851. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27852. this.onAfterActiveMeshesEvaluationObservable.clear();
  27853. this.onBeforeParticlesRenderingObservable.clear();
  27854. this.onAfterParticlesRenderingObservable.clear();
  27855. this.onBeforeSpritesRenderingObservable.clear();
  27856. this.onAfterSpritesRenderingObservable.clear();
  27857. this.onBeforeDrawPhaseObservable.clear();
  27858. this.onAfterDrawPhaseObservable.clear();
  27859. this.onBeforePhysicsObservable.clear();
  27860. this.onAfterPhysicsObservable.clear();
  27861. this.onBeforeAnimationsObservable.clear();
  27862. this.onAfterAnimationsObservable.clear();
  27863. this.onDataLoadedObservable.clear();
  27864. this.onBeforeRenderingGroupObservable.clear();
  27865. this.onAfterRenderingGroupObservable.clear();
  27866. this.detachControl();
  27867. // Release sounds & sounds tracks
  27868. if (BABYLON.AudioEngine) {
  27869. this.disposeSounds();
  27870. }
  27871. // VR Helper
  27872. if (this.VRHelper) {
  27873. this.VRHelper.dispose();
  27874. }
  27875. // Detach cameras
  27876. var canvas = this._engine.getRenderingCanvas();
  27877. if (canvas) {
  27878. var index;
  27879. for (index = 0; index < this.cameras.length; index++) {
  27880. this.cameras[index].detachControl(canvas);
  27881. }
  27882. }
  27883. // Release animation groups
  27884. while (this.animationGroups.length) {
  27885. this.animationGroups[0].dispose();
  27886. }
  27887. // Release lights
  27888. while (this.lights.length) {
  27889. this.lights[0].dispose();
  27890. }
  27891. // Release meshes
  27892. while (this.meshes.length) {
  27893. this.meshes[0].dispose(true);
  27894. }
  27895. while (this.transformNodes.length) {
  27896. this.removeTransformNode(this.transformNodes[0]);
  27897. }
  27898. // Release cameras
  27899. while (this.cameras.length) {
  27900. this.cameras[0].dispose();
  27901. }
  27902. // Release materials
  27903. if (this.defaultMaterial) {
  27904. this.defaultMaterial.dispose();
  27905. }
  27906. while (this.multiMaterials.length) {
  27907. this.multiMaterials[0].dispose();
  27908. }
  27909. while (this.materials.length) {
  27910. this.materials[0].dispose();
  27911. }
  27912. // Release particles
  27913. while (this.particleSystems.length) {
  27914. this.particleSystems[0].dispose();
  27915. }
  27916. // Release sprites
  27917. while (this.spriteManagers.length) {
  27918. this.spriteManagers[0].dispose();
  27919. }
  27920. // Release postProcesses
  27921. while (this.postProcesses.length) {
  27922. this.postProcesses[0].dispose();
  27923. }
  27924. // Release textures
  27925. while (this.textures.length) {
  27926. this.textures[0].dispose();
  27927. }
  27928. // Release UBO
  27929. this._sceneUbo.dispose();
  27930. if (this._alternateSceneUbo) {
  27931. this._alternateSceneUbo.dispose();
  27932. }
  27933. // Post-processes
  27934. this.postProcessManager.dispose();
  27935. if (this._postProcessRenderPipelineManager) {
  27936. this._postProcessRenderPipelineManager.dispose();
  27937. }
  27938. // Physics
  27939. if (this._physicsEngine) {
  27940. this.disablePhysicsEngine();
  27941. }
  27942. // Remove from engine
  27943. index = this._engine.scenes.indexOf(this);
  27944. if (index > -1) {
  27945. this._engine.scenes.splice(index, 1);
  27946. }
  27947. this._engine.wipeCaches(true);
  27948. this._isDisposed = true;
  27949. };
  27950. Object.defineProperty(Scene.prototype, "isDisposed", {
  27951. /**
  27952. * Gets if the scene is already disposed
  27953. */
  27954. get: function () {
  27955. return this._isDisposed;
  27956. },
  27957. enumerable: true,
  27958. configurable: true
  27959. });
  27960. /**
  27961. * Releases sounds & soundtracks
  27962. */
  27963. Scene.prototype.disposeSounds = function () {
  27964. if (!this._mainSoundTrack) {
  27965. return;
  27966. }
  27967. this.mainSoundTrack.dispose();
  27968. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27969. this.soundTracks[scIndex].dispose();
  27970. }
  27971. };
  27972. /**
  27973. * Call this function to reduce memory footprint of the scene.
  27974. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  27975. */
  27976. Scene.prototype.clearCachedVertexData = function () {
  27977. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27978. var mesh = this.meshes[meshIndex];
  27979. var geometry = mesh.geometry;
  27980. if (geometry) {
  27981. geometry._indices = [];
  27982. for (var vbName in geometry._vertexBuffers) {
  27983. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  27984. continue;
  27985. }
  27986. geometry._vertexBuffers[vbName]._buffer._data = null;
  27987. }
  27988. }
  27989. }
  27990. };
  27991. /**
  27992. * This function will remove the local cached buffer data from texture.
  27993. * It will save memory but will prevent the texture from being rebuilt
  27994. */
  27995. Scene.prototype.cleanCachedTextureBuffer = function () {
  27996. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27997. var baseTexture = _a[_i];
  27998. var buffer = baseTexture._buffer;
  27999. if (buffer) {
  28000. baseTexture._buffer = null;
  28001. }
  28002. }
  28003. };
  28004. // Octrees
  28005. /**
  28006. * Get the world extend vectors with an optional filter
  28007. *
  28008. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28009. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28010. */
  28011. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28012. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28013. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28014. filterPredicate = filterPredicate || (function () { return true; });
  28015. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28016. mesh.computeWorldMatrix(true);
  28017. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28018. return;
  28019. }
  28020. var boundingInfo = mesh.getBoundingInfo();
  28021. var minBox = boundingInfo.boundingBox.minimumWorld;
  28022. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28023. BABYLON.Tools.CheckExtends(minBox, min, max);
  28024. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28025. });
  28026. return {
  28027. min: min,
  28028. max: max
  28029. };
  28030. };
  28031. /**
  28032. * Creates or updates the octree used to boost selection (picking)
  28033. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28034. * @param maxCapacity defines the maximum capacity per leaf
  28035. * @param maxDepth defines the maximum depth of the octree
  28036. * @returns an octree of AbstractMesh
  28037. */
  28038. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28039. if (maxCapacity === void 0) { maxCapacity = 64; }
  28040. if (maxDepth === void 0) { maxDepth = 2; }
  28041. if (!this._selectionOctree) {
  28042. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28043. }
  28044. var worldExtends = this.getWorldExtends();
  28045. // Update octree
  28046. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28047. return this._selectionOctree;
  28048. };
  28049. // Picking
  28050. /**
  28051. * Creates a ray that can be used to pick in the scene
  28052. * @param x defines the x coordinate of the origin (on-screen)
  28053. * @param y defines the y coordinate of the origin (on-screen)
  28054. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28055. * @param camera defines the camera to use for the picking
  28056. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28057. * @returns a Ray
  28058. */
  28059. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28060. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28061. var result = BABYLON.Ray.Zero();
  28062. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28063. return result;
  28064. };
  28065. /**
  28066. * Creates a ray that can be used to pick in the scene
  28067. * @param x defines the x coordinate of the origin (on-screen)
  28068. * @param y defines the y coordinate of the origin (on-screen)
  28069. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28070. * @param result defines the ray where to store the picking ray
  28071. * @param camera defines the camera to use for the picking
  28072. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28073. * @returns the current scene
  28074. */
  28075. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28076. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28077. var engine = this._engine;
  28078. if (!camera) {
  28079. if (!this.activeCamera)
  28080. throw new Error("Active camera not set");
  28081. camera = this.activeCamera;
  28082. }
  28083. var cameraViewport = camera.viewport;
  28084. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28085. // Moving coordinates to local viewport world
  28086. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28087. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28088. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28089. return this;
  28090. };
  28091. /**
  28092. * Creates a ray that can be used to pick in the scene
  28093. * @param x defines the x coordinate of the origin (on-screen)
  28094. * @param y defines the y coordinate of the origin (on-screen)
  28095. * @param camera defines the camera to use for the picking
  28096. * @returns a Ray
  28097. */
  28098. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28099. var result = BABYLON.Ray.Zero();
  28100. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28101. return result;
  28102. };
  28103. /**
  28104. * Creates a ray that can be used to pick in the scene
  28105. * @param x defines the x coordinate of the origin (on-screen)
  28106. * @param y defines the y coordinate of the origin (on-screen)
  28107. * @param result defines the ray where to store the picking ray
  28108. * @param camera defines the camera to use for the picking
  28109. * @returns the current scene
  28110. */
  28111. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28112. if (!BABYLON.PickingInfo) {
  28113. return this;
  28114. }
  28115. var engine = this._engine;
  28116. if (!camera) {
  28117. if (!this.activeCamera)
  28118. throw new Error("Active camera not set");
  28119. camera = this.activeCamera;
  28120. }
  28121. var cameraViewport = camera.viewport;
  28122. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28123. var identity = BABYLON.Matrix.Identity();
  28124. // Moving coordinates to local viewport world
  28125. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28126. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28127. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28128. return this;
  28129. };
  28130. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28131. if (!BABYLON.PickingInfo) {
  28132. return null;
  28133. }
  28134. var pickingInfo = null;
  28135. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28136. var mesh = this.meshes[meshIndex];
  28137. if (predicate) {
  28138. if (!predicate(mesh)) {
  28139. continue;
  28140. }
  28141. }
  28142. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28143. continue;
  28144. }
  28145. var world = mesh.getWorldMatrix();
  28146. var ray = rayFunction(world);
  28147. var result = mesh.intersects(ray, fastCheck);
  28148. if (!result || !result.hit)
  28149. continue;
  28150. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28151. continue;
  28152. pickingInfo = result;
  28153. if (fastCheck) {
  28154. break;
  28155. }
  28156. }
  28157. return pickingInfo || new BABYLON.PickingInfo();
  28158. };
  28159. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28160. if (!BABYLON.PickingInfo) {
  28161. return null;
  28162. }
  28163. var pickingInfos = new Array();
  28164. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28165. var mesh = this.meshes[meshIndex];
  28166. if (predicate) {
  28167. if (!predicate(mesh)) {
  28168. continue;
  28169. }
  28170. }
  28171. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28172. continue;
  28173. }
  28174. var world = mesh.getWorldMatrix();
  28175. var ray = rayFunction(world);
  28176. var result = mesh.intersects(ray, false);
  28177. if (!result || !result.hit)
  28178. continue;
  28179. pickingInfos.push(result);
  28180. }
  28181. return pickingInfos;
  28182. };
  28183. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28184. if (!BABYLON.PickingInfo) {
  28185. return null;
  28186. }
  28187. var pickingInfo = null;
  28188. if (!camera) {
  28189. if (!this.activeCamera) {
  28190. return null;
  28191. }
  28192. camera = this.activeCamera;
  28193. }
  28194. if (this.spriteManagers.length > 0) {
  28195. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28196. var spriteManager = this.spriteManagers[spriteIndex];
  28197. if (!spriteManager.isPickable) {
  28198. continue;
  28199. }
  28200. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28201. if (!result || !result.hit)
  28202. continue;
  28203. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28204. continue;
  28205. pickingInfo = result;
  28206. if (fastCheck) {
  28207. break;
  28208. }
  28209. }
  28210. }
  28211. return pickingInfo || new BABYLON.PickingInfo();
  28212. };
  28213. /** Launch a ray to try to pick a mesh in the scene
  28214. * @param x position on screen
  28215. * @param y position on screen
  28216. * @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
  28217. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28218. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28219. * @returns a PickingInfo
  28220. */
  28221. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28222. var _this = this;
  28223. if (!BABYLON.PickingInfo) {
  28224. return null;
  28225. }
  28226. var result = this._internalPick(function (world) {
  28227. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28228. return _this._tempPickingRay;
  28229. }, predicate, fastCheck);
  28230. if (result) {
  28231. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28232. }
  28233. return result;
  28234. };
  28235. /** Launch a ray to try to pick a sprite in the scene
  28236. * @param x position on screen
  28237. * @param y position on screen
  28238. * @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
  28239. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28240. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28241. * @returns a PickingInfo
  28242. */
  28243. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28244. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28245. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28246. };
  28247. /** Use the given ray to pick a mesh in the scene
  28248. * @param ray The ray to use to pick meshes
  28249. * @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
  28250. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28251. * @returns a PickingInfo
  28252. */
  28253. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28254. var _this = this;
  28255. var result = this._internalPick(function (world) {
  28256. if (!_this._pickWithRayInverseMatrix) {
  28257. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28258. }
  28259. world.invertToRef(_this._pickWithRayInverseMatrix);
  28260. if (!_this._cachedRayForTransform) {
  28261. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28262. }
  28263. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28264. return _this._cachedRayForTransform;
  28265. }, predicate, fastCheck);
  28266. if (result) {
  28267. result.ray = ray;
  28268. }
  28269. return result;
  28270. };
  28271. /**
  28272. * Launch a ray to try to pick a mesh in the scene
  28273. * @param x X position on screen
  28274. * @param y Y position on screen
  28275. * @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
  28276. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28277. * @returns an array of PickingInfo
  28278. */
  28279. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28280. var _this = this;
  28281. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28282. };
  28283. /**
  28284. * Launch a ray to try to pick a mesh in the scene
  28285. * @param ray Ray to use
  28286. * @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
  28287. * @returns an array of PickingInfo
  28288. */
  28289. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28290. var _this = this;
  28291. return this._internalMultiPick(function (world) {
  28292. if (!_this._pickWithRayInverseMatrix) {
  28293. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28294. }
  28295. world.invertToRef(_this._pickWithRayInverseMatrix);
  28296. if (!_this._cachedRayForTransform) {
  28297. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28298. }
  28299. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28300. return _this._cachedRayForTransform;
  28301. }, predicate);
  28302. };
  28303. /**
  28304. * Force the value of meshUnderPointer
  28305. * @param mesh defines the mesh to use
  28306. */
  28307. Scene.prototype.setPointerOverMesh = function (mesh) {
  28308. if (this._pointerOverMesh === mesh) {
  28309. return;
  28310. }
  28311. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28312. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28313. }
  28314. this._pointerOverMesh = mesh;
  28315. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28316. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28317. }
  28318. };
  28319. /**
  28320. * Gets the mesh under the pointer
  28321. * @returns a Mesh or null if no mesh is under the pointer
  28322. */
  28323. Scene.prototype.getPointerOverMesh = function () {
  28324. return this._pointerOverMesh;
  28325. };
  28326. /**
  28327. * Force the sprite under the pointer
  28328. * @param sprite defines the sprite to use
  28329. */
  28330. Scene.prototype.setPointerOverSprite = function (sprite) {
  28331. if (this._pointerOverSprite === sprite) {
  28332. return;
  28333. }
  28334. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28335. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28336. }
  28337. this._pointerOverSprite = sprite;
  28338. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28339. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28340. }
  28341. };
  28342. /**
  28343. * Gets the sprite under the pointer
  28344. * @returns a Sprite or null if no sprite is under the pointer
  28345. */
  28346. Scene.prototype.getPointerOverSprite = function () {
  28347. return this._pointerOverSprite;
  28348. };
  28349. // Physics
  28350. /**
  28351. * Gets the current physics engine
  28352. * @returns a PhysicsEngine or null if none attached
  28353. */
  28354. Scene.prototype.getPhysicsEngine = function () {
  28355. return this._physicsEngine;
  28356. };
  28357. /**
  28358. * Enables physics to the current scene
  28359. * @param gravity defines the scene's gravity for the physics engine
  28360. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28361. * @return a boolean indicating if the physics engine was initialized
  28362. */
  28363. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28364. if (gravity === void 0) { gravity = null; }
  28365. if (this._physicsEngine) {
  28366. return true;
  28367. }
  28368. try {
  28369. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28370. return true;
  28371. }
  28372. catch (e) {
  28373. BABYLON.Tools.Error(e.message);
  28374. return false;
  28375. }
  28376. };
  28377. /**
  28378. * Disables and disposes the physics engine associated with the scene
  28379. */
  28380. Scene.prototype.disablePhysicsEngine = function () {
  28381. if (!this._physicsEngine) {
  28382. return;
  28383. }
  28384. this._physicsEngine.dispose();
  28385. this._physicsEngine = null;
  28386. };
  28387. /**
  28388. * Gets a boolean indicating if there is an active physics engine
  28389. * @returns a boolean indicating if there is an active physics engine
  28390. */
  28391. Scene.prototype.isPhysicsEnabled = function () {
  28392. return this._physicsEngine !== undefined;
  28393. };
  28394. /**
  28395. * Deletes a physics compound impostor
  28396. * @param compound defines the compound to delete
  28397. */
  28398. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28399. var mesh = compound.parts[0].mesh;
  28400. if (mesh.physicsImpostor) {
  28401. mesh.physicsImpostor.dispose( /*true*/);
  28402. mesh.physicsImpostor = null;
  28403. }
  28404. };
  28405. // Misc.
  28406. /** @hidden */
  28407. Scene.prototype._rebuildGeometries = function () {
  28408. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28409. var geometry = _a[_i];
  28410. geometry._rebuild();
  28411. }
  28412. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28413. var mesh = _c[_b];
  28414. mesh._rebuild();
  28415. }
  28416. if (this.postProcessManager) {
  28417. this.postProcessManager._rebuild();
  28418. }
  28419. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28420. var component = _e[_d];
  28421. component.rebuild();
  28422. }
  28423. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28424. var system = _g[_f];
  28425. system.rebuild();
  28426. }
  28427. if (this._postProcessRenderPipelineManager) {
  28428. this._postProcessRenderPipelineManager._rebuild();
  28429. }
  28430. };
  28431. /** @hidden */
  28432. Scene.prototype._rebuildTextures = function () {
  28433. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28434. var texture = _a[_i];
  28435. texture._rebuild();
  28436. }
  28437. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28438. };
  28439. /**
  28440. * Creates a default light for the scene.
  28441. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28442. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28443. */
  28444. Scene.prototype.createDefaultLight = function (replace) {
  28445. if (replace === void 0) { replace = false; }
  28446. // Dispose existing light in replace mode.
  28447. if (replace) {
  28448. if (this.lights) {
  28449. for (var i = 0; i < this.lights.length; i++) {
  28450. this.lights[i].dispose();
  28451. }
  28452. }
  28453. }
  28454. // Light
  28455. if (this.lights.length === 0) {
  28456. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28457. }
  28458. };
  28459. /**
  28460. * Creates a default camera for the scene.
  28461. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28462. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28463. * @param replace has default false, when true replaces the active camera in the scene
  28464. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28465. */
  28466. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28467. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28468. if (replace === void 0) { replace = false; }
  28469. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28470. // Dispose existing camera in replace mode.
  28471. if (replace) {
  28472. if (this.activeCamera) {
  28473. this.activeCamera.dispose();
  28474. this.activeCamera = null;
  28475. }
  28476. }
  28477. // Camera
  28478. if (!this.activeCamera) {
  28479. var worldExtends = this.getWorldExtends();
  28480. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28481. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28482. var camera;
  28483. var radius = worldSize.length() * 1.5;
  28484. // empty scene scenario!
  28485. if (!isFinite(radius)) {
  28486. radius = 1;
  28487. worldCenter.copyFromFloats(0, 0, 0);
  28488. }
  28489. if (createArcRotateCamera) {
  28490. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28491. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28492. arcRotateCamera.wheelPrecision = 100 / radius;
  28493. camera = arcRotateCamera;
  28494. }
  28495. else {
  28496. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28497. freeCamera.setTarget(worldCenter);
  28498. camera = freeCamera;
  28499. }
  28500. camera.minZ = radius * 0.01;
  28501. camera.maxZ = radius * 1000;
  28502. camera.speed = radius * 0.2;
  28503. this.activeCamera = camera;
  28504. var canvas = this.getEngine().getRenderingCanvas();
  28505. if (attachCameraControls && canvas) {
  28506. camera.attachControl(canvas);
  28507. }
  28508. }
  28509. };
  28510. /**
  28511. * Creates a default camera and a default light.
  28512. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28513. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28514. * @param replace has the default false, when true replaces the active camera/light in the scene
  28515. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28516. */
  28517. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28518. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28519. if (replace === void 0) { replace = false; }
  28520. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28521. this.createDefaultLight(replace);
  28522. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28523. };
  28524. /**
  28525. * Creates a new sky box
  28526. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28527. * @param environmentTexture defines the texture to use as environment texture
  28528. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28529. * @param scale defines the overall scale of the skybox
  28530. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28531. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28532. * @returns a new mesh holding the sky box
  28533. */
  28534. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28535. if (pbr === void 0) { pbr = false; }
  28536. if (scale === void 0) { scale = 1000; }
  28537. if (blur === void 0) { blur = 0; }
  28538. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28539. if (!environmentTexture) {
  28540. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28541. return null;
  28542. }
  28543. if (setGlobalEnvTexture) {
  28544. if (environmentTexture) {
  28545. this.environmentTexture = environmentTexture;
  28546. }
  28547. }
  28548. // Skybox
  28549. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28550. if (pbr) {
  28551. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28552. hdrSkyboxMaterial.backFaceCulling = false;
  28553. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28554. if (hdrSkyboxMaterial.reflectionTexture) {
  28555. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28556. }
  28557. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28558. hdrSkyboxMaterial.disableLighting = true;
  28559. hdrSkyboxMaterial.twoSidedLighting = true;
  28560. hdrSkybox.infiniteDistance = true;
  28561. hdrSkybox.material = hdrSkyboxMaterial;
  28562. }
  28563. else {
  28564. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28565. skyboxMaterial.backFaceCulling = false;
  28566. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28567. if (skyboxMaterial.reflectionTexture) {
  28568. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28569. }
  28570. skyboxMaterial.disableLighting = true;
  28571. hdrSkybox.infiniteDistance = true;
  28572. hdrSkybox.material = skyboxMaterial;
  28573. }
  28574. return hdrSkybox;
  28575. };
  28576. /**
  28577. * Creates a new environment
  28578. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28579. * @param options defines the options you can use to configure the environment
  28580. * @returns the new EnvironmentHelper
  28581. */
  28582. Scene.prototype.createDefaultEnvironment = function (options) {
  28583. if (BABYLON.EnvironmentHelper) {
  28584. return new BABYLON.EnvironmentHelper(options, this);
  28585. }
  28586. return null;
  28587. };
  28588. /**
  28589. * Creates a new VREXperienceHelper
  28590. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28591. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28592. * @returns a new VREXperienceHelper
  28593. */
  28594. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28595. if (webVROptions === void 0) { webVROptions = {}; }
  28596. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28597. };
  28598. // Tags
  28599. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28600. if (tagsQuery === undefined) {
  28601. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28602. return list;
  28603. }
  28604. var listByTags = [];
  28605. forEach = forEach || (function (item) { return; });
  28606. for (var i in list) {
  28607. var item = list[i];
  28608. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28609. listByTags.push(item);
  28610. forEach(item);
  28611. }
  28612. }
  28613. return listByTags;
  28614. };
  28615. /**
  28616. * Get a list of meshes by tags
  28617. * @param tagsQuery defines the tags query to use
  28618. * @param forEach defines a predicate used to filter results
  28619. * @returns an array of Mesh
  28620. */
  28621. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28622. return this._getByTags(this.meshes, tagsQuery, forEach);
  28623. };
  28624. /**
  28625. * Get a list of cameras by tags
  28626. * @param tagsQuery defines the tags query to use
  28627. * @param forEach defines a predicate used to filter results
  28628. * @returns an array of Camera
  28629. */
  28630. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28631. return this._getByTags(this.cameras, tagsQuery, forEach);
  28632. };
  28633. /**
  28634. * Get a list of lights by tags
  28635. * @param tagsQuery defines the tags query to use
  28636. * @param forEach defines a predicate used to filter results
  28637. * @returns an array of Light
  28638. */
  28639. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28640. return this._getByTags(this.lights, tagsQuery, forEach);
  28641. };
  28642. /**
  28643. * Get a list of materials by tags
  28644. * @param tagsQuery defines the tags query to use
  28645. * @param forEach defines a predicate used to filter results
  28646. * @returns an array of Material
  28647. */
  28648. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28649. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28650. };
  28651. /**
  28652. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28653. * This allowed control for front to back rendering or reversly depending of the special needs.
  28654. *
  28655. * @param renderingGroupId The rendering group id corresponding to its index
  28656. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28657. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28658. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28659. */
  28660. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28661. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28662. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28663. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28664. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28665. };
  28666. /**
  28667. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28668. *
  28669. * @param renderingGroupId The rendering group id corresponding to its index
  28670. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28671. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28672. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28673. */
  28674. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28675. if (depth === void 0) { depth = true; }
  28676. if (stencil === void 0) { stencil = true; }
  28677. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28678. };
  28679. /**
  28680. * Gets the current auto clear configuration for one rendering group of the rendering
  28681. * manager.
  28682. * @param index the rendering group index to get the information for
  28683. * @returns The auto clear setup for the requested rendering group
  28684. */
  28685. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28686. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28687. };
  28688. /**
  28689. * Will flag all materials as dirty to trigger new shader compilation
  28690. * @param flag defines the flag used to specify which material part must be marked as dirty
  28691. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28692. */
  28693. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28694. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28695. var material = _a[_i];
  28696. if (predicate && !predicate(material)) {
  28697. continue;
  28698. }
  28699. material.markAsDirty(flag);
  28700. }
  28701. };
  28702. /** @hidden */
  28703. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28704. var _this = this;
  28705. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28706. this._activeRequests.push(request);
  28707. request.onCompleteObservable.add(function (request) {
  28708. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28709. });
  28710. return request;
  28711. };
  28712. /** @hidden */
  28713. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28714. var _this = this;
  28715. return new Promise(function (resolve, reject) {
  28716. _this._loadFile(url, function (data) {
  28717. resolve(data);
  28718. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28719. reject(exception);
  28720. });
  28721. });
  28722. };
  28723. // Statics
  28724. Scene._FOGMODE_NONE = 0;
  28725. Scene._FOGMODE_EXP = 1;
  28726. Scene._FOGMODE_EXP2 = 2;
  28727. Scene._FOGMODE_LINEAR = 3;
  28728. Scene._uniqueIdCounter = 0;
  28729. /**
  28730. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28731. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28732. */
  28733. Scene.MinDeltaTime = 1.0;
  28734. /**
  28735. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28736. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28737. */
  28738. Scene.MaxDeltaTime = 1000.0;
  28739. /** The distance in pixel that you have to move to prevent some events */
  28740. Scene.DragMovementThreshold = 10; // in pixels
  28741. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28742. Scene.LongPressDelay = 500; // in milliseconds
  28743. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28744. Scene.DoubleClickDelay = 300; // in milliseconds
  28745. /** If you need to check double click without raising a single click at first click, enable this flag */
  28746. Scene.ExclusiveDoubleClickMode = false;
  28747. return Scene;
  28748. }(BABYLON.AbstractScene));
  28749. BABYLON.Scene = Scene;
  28750. })(BABYLON || (BABYLON = {}));
  28751. //# sourceMappingURL=babylon.scene.js.map
  28752. var BABYLON;
  28753. (function (BABYLON) {
  28754. /**
  28755. * Set of assets to keep when moving a scene into an asset container.
  28756. */
  28757. var KeepAssets = /** @class */ (function (_super) {
  28758. __extends(KeepAssets, _super);
  28759. function KeepAssets() {
  28760. return _super !== null && _super.apply(this, arguments) || this;
  28761. }
  28762. return KeepAssets;
  28763. }(BABYLON.AbstractScene));
  28764. BABYLON.KeepAssets = KeepAssets;
  28765. /**
  28766. * Container with a set of assets that can be added or removed from a scene.
  28767. */
  28768. var AssetContainer = /** @class */ (function (_super) {
  28769. __extends(AssetContainer, _super);
  28770. /**
  28771. * Instantiates an AssetContainer.
  28772. * @param scene The scene the AssetContainer belongs to.
  28773. */
  28774. function AssetContainer(scene) {
  28775. var _this = _super.call(this) || this;
  28776. _this.scene = scene;
  28777. return _this;
  28778. }
  28779. /**
  28780. * Adds all the assets from the container to the scene.
  28781. */
  28782. AssetContainer.prototype.addAllToScene = function () {
  28783. var _this = this;
  28784. this.cameras.forEach(function (o) {
  28785. _this.scene.addCamera(o);
  28786. });
  28787. this.lights.forEach(function (o) {
  28788. _this.scene.addLight(o);
  28789. });
  28790. this.meshes.forEach(function (o) {
  28791. _this.scene.addMesh(o);
  28792. });
  28793. this.skeletons.forEach(function (o) {
  28794. _this.scene.addSkeleton(o);
  28795. });
  28796. this.animations.forEach(function (o) {
  28797. _this.scene.addAnimation(o);
  28798. });
  28799. this.animationGroups.forEach(function (o) {
  28800. _this.scene.addAnimationGroup(o);
  28801. });
  28802. this.multiMaterials.forEach(function (o) {
  28803. _this.scene.addMultiMaterial(o);
  28804. });
  28805. this.materials.forEach(function (o) {
  28806. _this.scene.addMaterial(o);
  28807. });
  28808. this.morphTargetManagers.forEach(function (o) {
  28809. _this.scene.addMorphTargetManager(o);
  28810. });
  28811. this.geometries.forEach(function (o) {
  28812. _this.scene.addGeometry(o);
  28813. });
  28814. this.transformNodes.forEach(function (o) {
  28815. _this.scene.addTransformNode(o);
  28816. });
  28817. this.actionManagers.forEach(function (o) {
  28818. _this.scene.addActionManager(o);
  28819. });
  28820. this.sounds.forEach(function (o) {
  28821. o.play();
  28822. o.autoplay = true;
  28823. _this.scene.mainSoundTrack.AddSound(o);
  28824. });
  28825. this.textures.forEach(function (o) {
  28826. _this.scene.addTexture(o);
  28827. });
  28828. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28829. var component = _a[_i];
  28830. component.addFromContainer(this.scene);
  28831. }
  28832. };
  28833. /**
  28834. * Removes all the assets in the container from the scene
  28835. */
  28836. AssetContainer.prototype.removeAllFromScene = function () {
  28837. var _this = this;
  28838. this.cameras.forEach(function (o) {
  28839. _this.scene.removeCamera(o);
  28840. });
  28841. this.lights.forEach(function (o) {
  28842. _this.scene.removeLight(o);
  28843. });
  28844. this.meshes.forEach(function (o) {
  28845. _this.scene.removeMesh(o);
  28846. });
  28847. this.skeletons.forEach(function (o) {
  28848. _this.scene.removeSkeleton(o);
  28849. });
  28850. this.animations.forEach(function (o) {
  28851. _this.scene.removeAnimation(o);
  28852. });
  28853. this.animationGroups.forEach(function (o) {
  28854. _this.scene.removeAnimationGroup(o);
  28855. });
  28856. this.multiMaterials.forEach(function (o) {
  28857. _this.scene.removeMultiMaterial(o);
  28858. });
  28859. this.materials.forEach(function (o) {
  28860. _this.scene.removeMaterial(o);
  28861. });
  28862. this.morphTargetManagers.forEach(function (o) {
  28863. _this.scene.removeMorphTargetManager(o);
  28864. });
  28865. this.geometries.forEach(function (o) {
  28866. _this.scene.removeGeometry(o);
  28867. });
  28868. this.transformNodes.forEach(function (o) {
  28869. _this.scene.removeTransformNode(o);
  28870. });
  28871. this.actionManagers.forEach(function (o) {
  28872. _this.scene.removeActionManager(o);
  28873. });
  28874. this.sounds.forEach(function (o) {
  28875. o.stop();
  28876. o.autoplay = false;
  28877. _this.scene.mainSoundTrack.RemoveSound(o);
  28878. });
  28879. this.textures.forEach(function (o) {
  28880. _this.scene.removeTexture(o);
  28881. });
  28882. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28883. var component = _a[_i];
  28884. component.removeFromContainer(this.scene);
  28885. }
  28886. };
  28887. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28888. if (!sourceAssets) {
  28889. return;
  28890. }
  28891. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28892. var asset = sourceAssets_1[_i];
  28893. var move = true;
  28894. if (keepAssets) {
  28895. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28896. var keepAsset = keepAssets_1[_a];
  28897. if (asset === keepAsset) {
  28898. move = false;
  28899. break;
  28900. }
  28901. }
  28902. }
  28903. if (move) {
  28904. targetAssets.push(asset);
  28905. }
  28906. }
  28907. };
  28908. /**
  28909. * Removes all the assets contained in the scene and adds them to the container.
  28910. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28911. */
  28912. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28913. if (keepAssets === undefined) {
  28914. keepAssets = new KeepAssets();
  28915. }
  28916. for (var key in this) {
  28917. if (this.hasOwnProperty(key)) {
  28918. this[key] = this[key] || [];
  28919. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28920. }
  28921. }
  28922. this.removeAllFromScene();
  28923. };
  28924. /**
  28925. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  28926. * @returns the root mesh
  28927. */
  28928. AssetContainer.prototype.createRootMesh = function () {
  28929. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28930. this.meshes.forEach(function (m) {
  28931. if (!m.parent) {
  28932. rootMesh.addChild(m);
  28933. }
  28934. });
  28935. this.meshes.unshift(rootMesh);
  28936. return rootMesh;
  28937. };
  28938. return AssetContainer;
  28939. }(BABYLON.AbstractScene));
  28940. BABYLON.AssetContainer = AssetContainer;
  28941. })(BABYLON || (BABYLON = {}));
  28942. //# sourceMappingURL=babylon.assetContainer.js.map
  28943. var BABYLON;
  28944. (function (BABYLON) {
  28945. var Buffer = /** @class */ (function () {
  28946. /**
  28947. * Constructor
  28948. * @param engine the engine
  28949. * @param data the data to use for this buffer
  28950. * @param updatable whether the data is updatable
  28951. * @param stride the stride (optional)
  28952. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28953. * @param instanced whether the buffer is instanced (optional)
  28954. * @param useBytes set to true if the stride in in bytes (optional)
  28955. */
  28956. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28957. if (stride === void 0) { stride = 0; }
  28958. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28959. if (instanced === void 0) { instanced = false; }
  28960. if (useBytes === void 0) { useBytes = false; }
  28961. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28962. this._engine = engine.getScene().getEngine();
  28963. }
  28964. else {
  28965. this._engine = engine;
  28966. }
  28967. this._updatable = updatable;
  28968. this._instanced = instanced;
  28969. this._data = data;
  28970. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28971. if (!postponeInternalCreation) { // by default
  28972. this.create();
  28973. }
  28974. }
  28975. /**
  28976. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28977. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28978. * @param offset defines offset in the buffer (0 by default)
  28979. * @param size defines the size in floats of attributes (position is 3 for instance)
  28980. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28981. * @param instanced defines if the vertex buffer contains indexed data
  28982. * @param useBytes defines if the offset and stride are in bytes
  28983. * @returns the new vertex buffer
  28984. */
  28985. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28986. if (useBytes === void 0) { useBytes = false; }
  28987. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28988. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28989. // a lot of these parameters are ignored as they are overriden by the buffer
  28990. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28991. };
  28992. // Properties
  28993. Buffer.prototype.isUpdatable = function () {
  28994. return this._updatable;
  28995. };
  28996. Buffer.prototype.getData = function () {
  28997. return this._data;
  28998. };
  28999. Buffer.prototype.getBuffer = function () {
  29000. return this._buffer;
  29001. };
  29002. /**
  29003. * Gets the stride in float32 units (i.e. byte stride / 4).
  29004. * May not be an integer if the byte stride is not divisible by 4.
  29005. * DEPRECATED. Use byteStride instead.
  29006. * @returns the stride in float32 units
  29007. */
  29008. Buffer.prototype.getStrideSize = function () {
  29009. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29010. };
  29011. // Methods
  29012. Buffer.prototype.create = function (data) {
  29013. if (data === void 0) { data = null; }
  29014. if (!data && this._buffer) {
  29015. return; // nothing to do
  29016. }
  29017. data = data || this._data;
  29018. if (!data) {
  29019. return;
  29020. }
  29021. if (!this._buffer) { // create buffer
  29022. if (this._updatable) {
  29023. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29024. this._data = data;
  29025. }
  29026. else {
  29027. this._buffer = this._engine.createVertexBuffer(data);
  29028. }
  29029. }
  29030. else if (this._updatable) { // update buffer
  29031. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29032. this._data = data;
  29033. }
  29034. };
  29035. Buffer.prototype._rebuild = function () {
  29036. this._buffer = null;
  29037. this.create(this._data);
  29038. };
  29039. Buffer.prototype.update = function (data) {
  29040. this.create(data);
  29041. };
  29042. /**
  29043. * Updates the data directly.
  29044. * @param data the new data
  29045. * @param offset the new offset
  29046. * @param vertexCount the vertex count (optional)
  29047. * @param useBytes set to true if the offset is in bytes
  29048. */
  29049. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29050. if (useBytes === void 0) { useBytes = false; }
  29051. if (!this._buffer) {
  29052. return;
  29053. }
  29054. if (this._updatable) { // update buffer
  29055. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29056. this._data = null;
  29057. }
  29058. };
  29059. Buffer.prototype.dispose = function () {
  29060. if (!this._buffer) {
  29061. return;
  29062. }
  29063. if (this._engine._releaseBuffer(this._buffer)) {
  29064. this._buffer = null;
  29065. }
  29066. };
  29067. return Buffer;
  29068. }());
  29069. BABYLON.Buffer = Buffer;
  29070. })(BABYLON || (BABYLON = {}));
  29071. //# sourceMappingURL=babylon.buffer.js.map
  29072. var BABYLON;
  29073. (function (BABYLON) {
  29074. var VertexBuffer = /** @class */ (function () {
  29075. /**
  29076. * Constructor
  29077. * @param engine the engine
  29078. * @param data the data to use for this vertex buffer
  29079. * @param kind the vertex buffer kind
  29080. * @param updatable whether the data is updatable
  29081. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29082. * @param stride the stride (optional)
  29083. * @param instanced whether the buffer is instanced (optional)
  29084. * @param offset the offset of the data (optional)
  29085. * @param size the number of components (optional)
  29086. * @param type the type of the component (optional)
  29087. * @param normalized whether the data contains normalized data (optional)
  29088. * @param useBytes set to true if stride and offset are in bytes (optional)
  29089. */
  29090. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29091. if (normalized === void 0) { normalized = false; }
  29092. if (useBytes === void 0) { useBytes = false; }
  29093. if (data instanceof BABYLON.Buffer) {
  29094. this._buffer = data;
  29095. this._ownsBuffer = false;
  29096. }
  29097. else {
  29098. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29099. this._ownsBuffer = true;
  29100. }
  29101. this._kind = kind;
  29102. if (type == undefined) {
  29103. var data_1 = this.getData();
  29104. this.type = VertexBuffer.FLOAT;
  29105. if (data_1 instanceof Int8Array)
  29106. this.type = VertexBuffer.BYTE;
  29107. else if (data_1 instanceof Uint8Array)
  29108. this.type = VertexBuffer.UNSIGNED_BYTE;
  29109. else if (data_1 instanceof Int16Array)
  29110. this.type = VertexBuffer.SHORT;
  29111. else if (data_1 instanceof Uint16Array)
  29112. this.type = VertexBuffer.UNSIGNED_SHORT;
  29113. else if (data_1 instanceof Int32Array)
  29114. this.type = VertexBuffer.INT;
  29115. else if (data_1 instanceof Uint32Array)
  29116. this.type = VertexBuffer.UNSIGNED_INT;
  29117. }
  29118. else {
  29119. this.type = type;
  29120. }
  29121. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29122. if (useBytes) {
  29123. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29124. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29125. this.byteOffset = offset || 0;
  29126. }
  29127. else {
  29128. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29129. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29130. this.byteOffset = (offset || 0) * typeByteLength;
  29131. }
  29132. this.normalized = normalized;
  29133. this._instanced = instanced !== undefined ? instanced : false;
  29134. this._instanceDivisor = instanced ? 1 : 0;
  29135. }
  29136. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29137. /**
  29138. * Gets or sets the instance divisor when in instanced mode
  29139. */
  29140. get: function () {
  29141. return this._instanceDivisor;
  29142. },
  29143. set: function (value) {
  29144. this._instanceDivisor = value;
  29145. if (value == 0) {
  29146. this._instanced = false;
  29147. }
  29148. else {
  29149. this._instanced = true;
  29150. }
  29151. },
  29152. enumerable: true,
  29153. configurable: true
  29154. });
  29155. VertexBuffer.prototype._rebuild = function () {
  29156. if (!this._buffer) {
  29157. return;
  29158. }
  29159. this._buffer._rebuild();
  29160. };
  29161. /**
  29162. * Returns the kind of the VertexBuffer (string).
  29163. */
  29164. VertexBuffer.prototype.getKind = function () {
  29165. return this._kind;
  29166. };
  29167. // Properties
  29168. /**
  29169. * Boolean : is the VertexBuffer updatable ?
  29170. */
  29171. VertexBuffer.prototype.isUpdatable = function () {
  29172. return this._buffer.isUpdatable();
  29173. };
  29174. /**
  29175. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29176. */
  29177. VertexBuffer.prototype.getData = function () {
  29178. return this._buffer.getData();
  29179. };
  29180. /**
  29181. * Returns the WebGLBuffer associated to the VertexBuffer.
  29182. */
  29183. VertexBuffer.prototype.getBuffer = function () {
  29184. return this._buffer.getBuffer();
  29185. };
  29186. /**
  29187. * Returns the stride as a multiple of the type byte length.
  29188. * DEPRECATED. Use byteStride instead.
  29189. */
  29190. VertexBuffer.prototype.getStrideSize = function () {
  29191. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29192. };
  29193. /**
  29194. * Returns the offset as a multiple of the type byte length.
  29195. * DEPRECATED. Use byteOffset instead.
  29196. */
  29197. VertexBuffer.prototype.getOffset = function () {
  29198. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29199. };
  29200. /**
  29201. * Returns the number of components per vertex attribute (integer).
  29202. */
  29203. VertexBuffer.prototype.getSize = function () {
  29204. return this._size;
  29205. };
  29206. /**
  29207. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29208. */
  29209. VertexBuffer.prototype.getIsInstanced = function () {
  29210. return this._instanced;
  29211. };
  29212. /**
  29213. * Returns the instancing divisor, zero for non-instanced (integer).
  29214. */
  29215. VertexBuffer.prototype.getInstanceDivisor = function () {
  29216. return this._instanceDivisor;
  29217. };
  29218. // Methods
  29219. /**
  29220. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29221. * Returns the created WebGLBuffer.
  29222. */
  29223. VertexBuffer.prototype.create = function (data) {
  29224. return this._buffer.create(data);
  29225. };
  29226. /**
  29227. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29228. * This function will create a new buffer if the current one is not updatable
  29229. * Returns the updated WebGLBuffer.
  29230. */
  29231. VertexBuffer.prototype.update = function (data) {
  29232. return this._buffer.update(data);
  29233. };
  29234. /**
  29235. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29236. * Returns the directly updated WebGLBuffer.
  29237. * @param data the new data
  29238. * @param offset the new offset
  29239. * @param useBytes set to true if the offset is in bytes
  29240. */
  29241. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29242. if (useBytes === void 0) { useBytes = false; }
  29243. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29244. };
  29245. /**
  29246. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29247. */
  29248. VertexBuffer.prototype.dispose = function () {
  29249. if (this._ownsBuffer) {
  29250. this._buffer.dispose();
  29251. }
  29252. };
  29253. /**
  29254. * Enumerates each value of this vertex buffer as numbers.
  29255. * @param count the number of values to enumerate
  29256. * @param callback the callback function called for each value
  29257. */
  29258. VertexBuffer.prototype.forEach = function (count, callback) {
  29259. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29260. };
  29261. Object.defineProperty(VertexBuffer, "PositionKind", {
  29262. get: function () {
  29263. return VertexBuffer._PositionKind;
  29264. },
  29265. enumerable: true,
  29266. configurable: true
  29267. });
  29268. Object.defineProperty(VertexBuffer, "NormalKind", {
  29269. get: function () {
  29270. return VertexBuffer._NormalKind;
  29271. },
  29272. enumerable: true,
  29273. configurable: true
  29274. });
  29275. Object.defineProperty(VertexBuffer, "TangentKind", {
  29276. get: function () {
  29277. return VertexBuffer._TangentKind;
  29278. },
  29279. enumerable: true,
  29280. configurable: true
  29281. });
  29282. Object.defineProperty(VertexBuffer, "UVKind", {
  29283. get: function () {
  29284. return VertexBuffer._UVKind;
  29285. },
  29286. enumerable: true,
  29287. configurable: true
  29288. });
  29289. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29290. get: function () {
  29291. return VertexBuffer._UV2Kind;
  29292. },
  29293. enumerable: true,
  29294. configurable: true
  29295. });
  29296. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29297. get: function () {
  29298. return VertexBuffer._UV3Kind;
  29299. },
  29300. enumerable: true,
  29301. configurable: true
  29302. });
  29303. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29304. get: function () {
  29305. return VertexBuffer._UV4Kind;
  29306. },
  29307. enumerable: true,
  29308. configurable: true
  29309. });
  29310. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29311. get: function () {
  29312. return VertexBuffer._UV5Kind;
  29313. },
  29314. enumerable: true,
  29315. configurable: true
  29316. });
  29317. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29318. get: function () {
  29319. return VertexBuffer._UV6Kind;
  29320. },
  29321. enumerable: true,
  29322. configurable: true
  29323. });
  29324. Object.defineProperty(VertexBuffer, "ColorKind", {
  29325. get: function () {
  29326. return VertexBuffer._ColorKind;
  29327. },
  29328. enumerable: true,
  29329. configurable: true
  29330. });
  29331. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29332. get: function () {
  29333. return VertexBuffer._MatricesIndicesKind;
  29334. },
  29335. enumerable: true,
  29336. configurable: true
  29337. });
  29338. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29339. get: function () {
  29340. return VertexBuffer._MatricesWeightsKind;
  29341. },
  29342. enumerable: true,
  29343. configurable: true
  29344. });
  29345. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29346. get: function () {
  29347. return VertexBuffer._MatricesIndicesExtraKind;
  29348. },
  29349. enumerable: true,
  29350. configurable: true
  29351. });
  29352. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29353. get: function () {
  29354. return VertexBuffer._MatricesWeightsExtraKind;
  29355. },
  29356. enumerable: true,
  29357. configurable: true
  29358. });
  29359. /**
  29360. * Deduces the stride given a kind.
  29361. * @param kind The kind string to deduce
  29362. * @returns The deduced stride
  29363. */
  29364. VertexBuffer.DeduceStride = function (kind) {
  29365. switch (kind) {
  29366. case VertexBuffer.UVKind:
  29367. case VertexBuffer.UV2Kind:
  29368. case VertexBuffer.UV3Kind:
  29369. case VertexBuffer.UV4Kind:
  29370. case VertexBuffer.UV5Kind:
  29371. case VertexBuffer.UV6Kind:
  29372. return 2;
  29373. case VertexBuffer.NormalKind:
  29374. case VertexBuffer.PositionKind:
  29375. return 3;
  29376. case VertexBuffer.ColorKind:
  29377. case VertexBuffer.MatricesIndicesKind:
  29378. case VertexBuffer.MatricesIndicesExtraKind:
  29379. case VertexBuffer.MatricesWeightsKind:
  29380. case VertexBuffer.MatricesWeightsExtraKind:
  29381. case VertexBuffer.TangentKind:
  29382. return 4;
  29383. default:
  29384. throw new Error("Invalid kind '" + kind + "'");
  29385. }
  29386. };
  29387. /**
  29388. * Gets the byte length of the given type.
  29389. * @param type the type
  29390. * @returns the number of bytes
  29391. */
  29392. VertexBuffer.GetTypeByteLength = function (type) {
  29393. switch (type) {
  29394. case VertexBuffer.BYTE:
  29395. case VertexBuffer.UNSIGNED_BYTE:
  29396. return 1;
  29397. case VertexBuffer.SHORT:
  29398. case VertexBuffer.UNSIGNED_SHORT:
  29399. return 2;
  29400. case VertexBuffer.INT:
  29401. case VertexBuffer.FLOAT:
  29402. return 4;
  29403. default:
  29404. throw new Error("Invalid type '" + type + "'");
  29405. }
  29406. };
  29407. /**
  29408. * Enumerates each value of the given parameters as numbers.
  29409. * @param data the data to enumerate
  29410. * @param byteOffset the byte offset of the data
  29411. * @param byteStride the byte stride of the data
  29412. * @param componentCount the number of components per element
  29413. * @param componentType the type of the component
  29414. * @param count the total number of components
  29415. * @param normalized whether the data is normalized
  29416. * @param callback the callback function called for each value
  29417. */
  29418. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29419. if (data instanceof Array) {
  29420. var offset = byteOffset / 4;
  29421. var stride = byteStride / 4;
  29422. for (var index = 0; index < count; index += componentCount) {
  29423. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29424. callback(data[offset + componentIndex], index + componentIndex);
  29425. }
  29426. offset += stride;
  29427. }
  29428. }
  29429. else {
  29430. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29431. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29432. for (var index = 0; index < count; index += componentCount) {
  29433. var componentByteOffset = byteOffset;
  29434. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29435. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29436. callback(value, index + componentIndex);
  29437. componentByteOffset += componentByteLength;
  29438. }
  29439. byteOffset += byteStride;
  29440. }
  29441. }
  29442. };
  29443. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29444. switch (type) {
  29445. case VertexBuffer.BYTE: {
  29446. var value = dataView.getInt8(byteOffset);
  29447. if (normalized) {
  29448. value = Math.max(value / 127, -1);
  29449. }
  29450. return value;
  29451. }
  29452. case VertexBuffer.UNSIGNED_BYTE: {
  29453. var value = dataView.getUint8(byteOffset);
  29454. if (normalized) {
  29455. value = value / 255;
  29456. }
  29457. return value;
  29458. }
  29459. case VertexBuffer.SHORT: {
  29460. var value = dataView.getInt16(byteOffset, true);
  29461. if (normalized) {
  29462. value = Math.max(value / 16383, -1);
  29463. }
  29464. return value;
  29465. }
  29466. case VertexBuffer.UNSIGNED_SHORT: {
  29467. var value = dataView.getUint16(byteOffset, true);
  29468. if (normalized) {
  29469. value = value / 65535;
  29470. }
  29471. return value;
  29472. }
  29473. case VertexBuffer.FLOAT: {
  29474. return dataView.getFloat32(byteOffset, true);
  29475. }
  29476. default: {
  29477. throw new Error("Invalid component type " + type);
  29478. }
  29479. }
  29480. };
  29481. /**
  29482. * The byte type.
  29483. */
  29484. VertexBuffer.BYTE = 5120;
  29485. /**
  29486. * The unsigned byte type.
  29487. */
  29488. VertexBuffer.UNSIGNED_BYTE = 5121;
  29489. /**
  29490. * The short type.
  29491. */
  29492. VertexBuffer.SHORT = 5122;
  29493. /**
  29494. * The unsigned short type.
  29495. */
  29496. VertexBuffer.UNSIGNED_SHORT = 5123;
  29497. /**
  29498. * The integer type.
  29499. */
  29500. VertexBuffer.INT = 5124;
  29501. /**
  29502. * The unsigned integer type.
  29503. */
  29504. VertexBuffer.UNSIGNED_INT = 5125;
  29505. /**
  29506. * The float type.
  29507. */
  29508. VertexBuffer.FLOAT = 5126;
  29509. // Enums
  29510. VertexBuffer._PositionKind = "position";
  29511. VertexBuffer._NormalKind = "normal";
  29512. VertexBuffer._TangentKind = "tangent";
  29513. VertexBuffer._UVKind = "uv";
  29514. VertexBuffer._UV2Kind = "uv2";
  29515. VertexBuffer._UV3Kind = "uv3";
  29516. VertexBuffer._UV4Kind = "uv4";
  29517. VertexBuffer._UV5Kind = "uv5";
  29518. VertexBuffer._UV6Kind = "uv6";
  29519. VertexBuffer._ColorKind = "color";
  29520. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29521. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29522. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29523. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29524. return VertexBuffer;
  29525. }());
  29526. BABYLON.VertexBuffer = VertexBuffer;
  29527. })(BABYLON || (BABYLON = {}));
  29528. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29529. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29530. var BABYLON;
  29531. (function (BABYLON) {
  29532. /**
  29533. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29534. */
  29535. var DummyInternalTextureTracker = /** @class */ (function () {
  29536. function DummyInternalTextureTracker() {
  29537. /**
  29538. * Gets or set the previous tracker in the list
  29539. */
  29540. this.previous = null;
  29541. /**
  29542. * Gets or set the next tracker in the list
  29543. */
  29544. this.next = null;
  29545. }
  29546. return DummyInternalTextureTracker;
  29547. }());
  29548. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29549. })(BABYLON || (BABYLON = {}));
  29550. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29551. var BABYLON;
  29552. (function (BABYLON) {
  29553. /**
  29554. * Class used to store data associated with WebGL texture data for the engine
  29555. * This class should not be used directly
  29556. */
  29557. var InternalTexture = /** @class */ (function () {
  29558. /**
  29559. * Creates a new InternalTexture
  29560. * @param engine defines the engine to use
  29561. * @param dataSource defines the type of data that will be used
  29562. */
  29563. function InternalTexture(engine, dataSource) {
  29564. /**
  29565. * Observable called when the texture is loaded
  29566. */
  29567. this.onLoadedObservable = new BABYLON.Observable();
  29568. /**
  29569. * Gets or set the previous tracker in the list
  29570. */
  29571. this.previous = null;
  29572. /**
  29573. * Gets or set the next tracker in the list
  29574. */
  29575. this.next = null;
  29576. // Private
  29577. /** @hidden */
  29578. this._initialSlot = -1;
  29579. /** @hidden */
  29580. this._designatedSlot = -1;
  29581. /** @hidden */
  29582. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29583. /** @hidden */
  29584. this._comparisonFunction = 0;
  29585. /** @hidden */
  29586. this._sphericalPolynomial = null;
  29587. /** @hidden */
  29588. this._lodGenerationScale = 0;
  29589. /** @hidden */
  29590. this._lodGenerationOffset = 0;
  29591. /** @hidden */
  29592. this._isRGBD = false;
  29593. /** @hidden */
  29594. this._references = 1;
  29595. this._engine = engine;
  29596. this._dataSource = dataSource;
  29597. this._webGLTexture = engine._createTexture();
  29598. }
  29599. /**
  29600. * Gets the Engine the texture belongs to.
  29601. * @returns The babylon engine
  29602. */
  29603. InternalTexture.prototype.getEngine = function () {
  29604. return this._engine;
  29605. };
  29606. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29607. /**
  29608. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29609. */
  29610. get: function () {
  29611. return this._dataSource;
  29612. },
  29613. enumerable: true,
  29614. configurable: true
  29615. });
  29616. /**
  29617. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29618. */
  29619. InternalTexture.prototype.incrementReferences = function () {
  29620. this._references++;
  29621. };
  29622. /**
  29623. * Change the size of the texture (not the size of the content)
  29624. * @param width defines the new width
  29625. * @param height defines the new height
  29626. * @param depth defines the new depth (1 by default)
  29627. */
  29628. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29629. if (depth === void 0) { depth = 1; }
  29630. this.width = width;
  29631. this.height = height;
  29632. this.depth = depth;
  29633. this.baseWidth = width;
  29634. this.baseHeight = height;
  29635. this.baseDepth = depth;
  29636. this._size = width * height * depth;
  29637. };
  29638. /** @hidden */
  29639. InternalTexture.prototype._rebuild = function () {
  29640. var _this = this;
  29641. var proxy;
  29642. this.isReady = false;
  29643. this._cachedCoordinatesMode = null;
  29644. this._cachedWrapU = null;
  29645. this._cachedWrapV = null;
  29646. this._cachedAnisotropicFilteringLevel = null;
  29647. switch (this._dataSource) {
  29648. case InternalTexture.DATASOURCE_TEMP:
  29649. return;
  29650. case InternalTexture.DATASOURCE_URL:
  29651. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29652. _this.isReady = true;
  29653. }, null, this._buffer, undefined, this.format);
  29654. proxy._swapAndDie(this);
  29655. return;
  29656. case InternalTexture.DATASOURCE_RAW:
  29657. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29658. proxy._swapAndDie(this);
  29659. this.isReady = true;
  29660. return;
  29661. case InternalTexture.DATASOURCE_RAW3D:
  29662. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29663. proxy._swapAndDie(this);
  29664. this.isReady = true;
  29665. return;
  29666. case InternalTexture.DATASOURCE_DYNAMIC:
  29667. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29668. proxy._swapAndDie(this);
  29669. // The engine will make sure to update content so no need to flag it as isReady = true
  29670. return;
  29671. case InternalTexture.DATASOURCE_RENDERTARGET:
  29672. var options = new BABYLON.RenderTargetCreationOptions();
  29673. options.generateDepthBuffer = this._generateDepthBuffer;
  29674. options.generateMipMaps = this.generateMipMaps;
  29675. options.generateStencilBuffer = this._generateStencilBuffer;
  29676. options.samplingMode = this.samplingMode;
  29677. options.type = this.type;
  29678. if (this.isCube) {
  29679. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29680. }
  29681. else {
  29682. var size = {
  29683. width: this.width,
  29684. height: this.height
  29685. };
  29686. proxy = this._engine.createRenderTargetTexture(size, options);
  29687. }
  29688. proxy._swapAndDie(this);
  29689. this.isReady = true;
  29690. return;
  29691. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29692. var depthTextureOptions = {
  29693. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29694. comparisonFunction: this._comparisonFunction,
  29695. generateStencil: this._generateStencilBuffer,
  29696. isCube: this.isCube
  29697. };
  29698. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29699. proxy._swapAndDie(this);
  29700. this.isReady = true;
  29701. return;
  29702. case InternalTexture.DATASOURCE_CUBE:
  29703. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29704. _this.isReady = true;
  29705. }, null, this.format, this._extension);
  29706. proxy._swapAndDie(this);
  29707. return;
  29708. case InternalTexture.DATASOURCE_CUBERAW:
  29709. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29710. proxy._swapAndDie(this);
  29711. this.isReady = true;
  29712. return;
  29713. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29714. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29715. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29716. _this.isReady = true;
  29717. });
  29718. proxy._swapAndDie(this);
  29719. return;
  29720. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29721. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29722. if (proxy) {
  29723. proxy._swapAndDie(_this);
  29724. }
  29725. _this.isReady = true;
  29726. }, null, this.format, this._extension);
  29727. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29728. return;
  29729. }
  29730. };
  29731. InternalTexture.prototype._swapAndDie = function (target) {
  29732. target._webGLTexture = this._webGLTexture;
  29733. if (this._framebuffer) {
  29734. target._framebuffer = this._framebuffer;
  29735. }
  29736. if (this._depthStencilBuffer) {
  29737. target._depthStencilBuffer = this._depthStencilBuffer;
  29738. }
  29739. if (this._lodTextureHigh) {
  29740. if (target._lodTextureHigh) {
  29741. target._lodTextureHigh.dispose();
  29742. }
  29743. target._lodTextureHigh = this._lodTextureHigh;
  29744. }
  29745. if (this._lodTextureMid) {
  29746. if (target._lodTextureMid) {
  29747. target._lodTextureMid.dispose();
  29748. }
  29749. target._lodTextureMid = this._lodTextureMid;
  29750. }
  29751. if (this._lodTextureLow) {
  29752. if (target._lodTextureLow) {
  29753. target._lodTextureLow.dispose();
  29754. }
  29755. target._lodTextureLow = this._lodTextureLow;
  29756. }
  29757. var cache = this._engine.getLoadedTexturesCache();
  29758. var index = cache.indexOf(this);
  29759. if (index !== -1) {
  29760. cache.splice(index, 1);
  29761. }
  29762. };
  29763. /**
  29764. * Dispose the current allocated resources
  29765. */
  29766. InternalTexture.prototype.dispose = function () {
  29767. if (!this._webGLTexture) {
  29768. return;
  29769. }
  29770. this._references--;
  29771. if (this._references === 0) {
  29772. this._engine._releaseTexture(this);
  29773. this._webGLTexture = null;
  29774. this.previous = null;
  29775. this.next = null;
  29776. }
  29777. };
  29778. /**
  29779. * The source of the texture data is unknown
  29780. */
  29781. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29782. /**
  29783. * Texture data comes from an URL
  29784. */
  29785. InternalTexture.DATASOURCE_URL = 1;
  29786. /**
  29787. * Texture data is only used for temporary storage
  29788. */
  29789. InternalTexture.DATASOURCE_TEMP = 2;
  29790. /**
  29791. * Texture data comes from raw data (ArrayBuffer)
  29792. */
  29793. InternalTexture.DATASOURCE_RAW = 3;
  29794. /**
  29795. * Texture content is dynamic (video or dynamic texture)
  29796. */
  29797. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29798. /**
  29799. * Texture content is generated by rendering to it
  29800. */
  29801. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29802. /**
  29803. * Texture content is part of a multi render target process
  29804. */
  29805. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29806. /**
  29807. * Texture data comes from a cube data file
  29808. */
  29809. InternalTexture.DATASOURCE_CUBE = 7;
  29810. /**
  29811. * Texture data comes from a raw cube data
  29812. */
  29813. InternalTexture.DATASOURCE_CUBERAW = 8;
  29814. /**
  29815. * Texture data come from a prefiltered cube data file
  29816. */
  29817. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29818. /**
  29819. * Texture content is raw 3D data
  29820. */
  29821. InternalTexture.DATASOURCE_RAW3D = 10;
  29822. /**
  29823. * Texture content is a depth texture
  29824. */
  29825. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29826. /**
  29827. * Texture data comes from a raw cube data encoded with RGBD
  29828. */
  29829. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29830. return InternalTexture;
  29831. }());
  29832. BABYLON.InternalTexture = InternalTexture;
  29833. })(BABYLON || (BABYLON = {}));
  29834. //# sourceMappingURL=babylon.internalTexture.js.map
  29835. var BABYLON;
  29836. (function (BABYLON) {
  29837. var BaseTexture = /** @class */ (function () {
  29838. function BaseTexture(scene) {
  29839. this._hasAlpha = false;
  29840. this.getAlphaFromRGB = false;
  29841. this.level = 1;
  29842. this.coordinatesIndex = 0;
  29843. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29844. /**
  29845. * | Value | Type | Description |
  29846. * | ----- | ------------------ | ----------- |
  29847. * | 0 | CLAMP_ADDRESSMODE | |
  29848. * | 1 | WRAP_ADDRESSMODE | |
  29849. * | 2 | MIRROR_ADDRESSMODE | |
  29850. */
  29851. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29852. /**
  29853. * | Value | Type | Description |
  29854. * | ----- | ------------------ | ----------- |
  29855. * | 0 | CLAMP_ADDRESSMODE | |
  29856. * | 1 | WRAP_ADDRESSMODE | |
  29857. * | 2 | MIRROR_ADDRESSMODE | |
  29858. */
  29859. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29860. /**
  29861. * | Value | Type | Description |
  29862. * | ----- | ------------------ | ----------- |
  29863. * | 0 | CLAMP_ADDRESSMODE | |
  29864. * | 1 | WRAP_ADDRESSMODE | |
  29865. * | 2 | MIRROR_ADDRESSMODE | |
  29866. */
  29867. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29868. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29869. this.isCube = false;
  29870. this.is3D = false;
  29871. this.gammaSpace = true;
  29872. this.invertZ = false;
  29873. this.lodLevelInAlpha = false;
  29874. this.isRenderTarget = false;
  29875. this.animations = new Array();
  29876. /**
  29877. * An event triggered when the texture is disposed.
  29878. */
  29879. this.onDisposeObservable = new BABYLON.Observable();
  29880. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29881. this._cachedSize = BABYLON.Size.Zero();
  29882. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29883. if (this._scene) {
  29884. this._scene.textures.push(this);
  29885. }
  29886. this._uid = null;
  29887. }
  29888. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29889. get: function () {
  29890. return this._hasAlpha;
  29891. },
  29892. set: function (value) {
  29893. if (this._hasAlpha === value) {
  29894. return;
  29895. }
  29896. this._hasAlpha = value;
  29897. if (this._scene) {
  29898. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29899. }
  29900. },
  29901. enumerable: true,
  29902. configurable: true
  29903. });
  29904. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29905. get: function () {
  29906. return this._coordinatesMode;
  29907. },
  29908. /**
  29909. * How a texture is mapped.
  29910. *
  29911. * | Value | Type | Description |
  29912. * | ----- | ----------------------------------- | ----------- |
  29913. * | 0 | EXPLICIT_MODE | |
  29914. * | 1 | SPHERICAL_MODE | |
  29915. * | 2 | PLANAR_MODE | |
  29916. * | 3 | CUBIC_MODE | |
  29917. * | 4 | PROJECTION_MODE | |
  29918. * | 5 | SKYBOX_MODE | |
  29919. * | 6 | INVCUBIC_MODE | |
  29920. * | 7 | EQUIRECTANGULAR_MODE | |
  29921. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29922. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29923. */
  29924. set: function (value) {
  29925. if (this._coordinatesMode === value) {
  29926. return;
  29927. }
  29928. this._coordinatesMode = value;
  29929. if (this._scene) {
  29930. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29931. }
  29932. },
  29933. enumerable: true,
  29934. configurable: true
  29935. });
  29936. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29937. /**
  29938. * Gets whether or not the texture contains RGBD data.
  29939. */
  29940. get: function () {
  29941. return this._texture != null && this._texture._isRGBD;
  29942. },
  29943. enumerable: true,
  29944. configurable: true
  29945. });
  29946. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29947. get: function () {
  29948. if (this._texture)
  29949. return this._texture._lodGenerationOffset;
  29950. return 0.0;
  29951. },
  29952. set: function (value) {
  29953. if (this._texture)
  29954. this._texture._lodGenerationOffset = value;
  29955. },
  29956. enumerable: true,
  29957. configurable: true
  29958. });
  29959. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29960. get: function () {
  29961. if (this._texture)
  29962. return this._texture._lodGenerationScale;
  29963. return 0.0;
  29964. },
  29965. set: function (value) {
  29966. if (this._texture)
  29967. this._texture._lodGenerationScale = value;
  29968. },
  29969. enumerable: true,
  29970. configurable: true
  29971. });
  29972. Object.defineProperty(BaseTexture.prototype, "uid", {
  29973. get: function () {
  29974. if (!this._uid) {
  29975. this._uid = BABYLON.Tools.RandomId();
  29976. }
  29977. return this._uid;
  29978. },
  29979. enumerable: true,
  29980. configurable: true
  29981. });
  29982. BaseTexture.prototype.toString = function () {
  29983. return this.name;
  29984. };
  29985. BaseTexture.prototype.getClassName = function () {
  29986. return "BaseTexture";
  29987. };
  29988. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29989. set: function (callback) {
  29990. if (this._onDisposeObserver) {
  29991. this.onDisposeObservable.remove(this._onDisposeObserver);
  29992. }
  29993. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29994. },
  29995. enumerable: true,
  29996. configurable: true
  29997. });
  29998. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29999. get: function () {
  30000. return true;
  30001. },
  30002. enumerable: true,
  30003. configurable: true
  30004. });
  30005. BaseTexture.prototype.getScene = function () {
  30006. return this._scene;
  30007. };
  30008. BaseTexture.prototype.getTextureMatrix = function () {
  30009. return BABYLON.Matrix.IdentityReadOnly;
  30010. };
  30011. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30012. return BABYLON.Matrix.IdentityReadOnly;
  30013. };
  30014. BaseTexture.prototype.getInternalTexture = function () {
  30015. return this._texture;
  30016. };
  30017. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30018. return !this.isBlocking || this.isReady();
  30019. };
  30020. BaseTexture.prototype.isReady = function () {
  30021. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30022. this.delayLoad();
  30023. return false;
  30024. }
  30025. if (this._texture) {
  30026. return this._texture.isReady;
  30027. }
  30028. return false;
  30029. };
  30030. BaseTexture.prototype.getSize = function () {
  30031. if (this._texture) {
  30032. if (this._texture.width) {
  30033. this._cachedSize.width = this._texture.width;
  30034. this._cachedSize.height = this._texture.height;
  30035. return this._cachedSize;
  30036. }
  30037. if (this._texture._size) {
  30038. this._cachedSize.width = this._texture._size;
  30039. this._cachedSize.height = this._texture._size;
  30040. return this._cachedSize;
  30041. }
  30042. }
  30043. return this._cachedSize;
  30044. };
  30045. BaseTexture.prototype.getBaseSize = function () {
  30046. if (!this.isReady() || !this._texture)
  30047. return BABYLON.Size.Zero();
  30048. if (this._texture._size) {
  30049. return new BABYLON.Size(this._texture._size, this._texture._size);
  30050. }
  30051. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30052. };
  30053. BaseTexture.prototype.scale = function (ratio) {
  30054. };
  30055. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30056. get: function () {
  30057. return false;
  30058. },
  30059. enumerable: true,
  30060. configurable: true
  30061. });
  30062. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30063. if (!this._scene) {
  30064. return null;
  30065. }
  30066. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30067. for (var index = 0; index < texturesCache.length; index++) {
  30068. var texturesCacheEntry = texturesCache[index];
  30069. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30070. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30071. texturesCacheEntry.incrementReferences();
  30072. return texturesCacheEntry;
  30073. }
  30074. }
  30075. }
  30076. return null;
  30077. };
  30078. BaseTexture.prototype._rebuild = function () {
  30079. };
  30080. BaseTexture.prototype.delayLoad = function () {
  30081. };
  30082. BaseTexture.prototype.clone = function () {
  30083. return null;
  30084. };
  30085. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30086. get: function () {
  30087. if (!this._texture) {
  30088. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30089. }
  30090. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30091. },
  30092. enumerable: true,
  30093. configurable: true
  30094. });
  30095. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30096. get: function () {
  30097. if (!this._texture) {
  30098. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30099. }
  30100. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30101. },
  30102. enumerable: true,
  30103. configurable: true
  30104. });
  30105. /**
  30106. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30107. * This will returns an RGBA array buffer containing either in values (0-255) or
  30108. * float values (0-1) depending of the underlying buffer type.
  30109. * @param faceIndex The face of the texture to read (in case of cube texture)
  30110. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30111. * @returns The Array buffer containing the pixels data.
  30112. */
  30113. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30114. if (faceIndex === void 0) { faceIndex = 0; }
  30115. if (level === void 0) { level = 0; }
  30116. if (!this._texture) {
  30117. return null;
  30118. }
  30119. var size = this.getSize();
  30120. var width = size.width;
  30121. var height = size.height;
  30122. var scene = this.getScene();
  30123. if (!scene) {
  30124. return null;
  30125. }
  30126. var engine = scene.getEngine();
  30127. if (level != 0) {
  30128. width = width / Math.pow(2, level);
  30129. height = height / Math.pow(2, level);
  30130. width = Math.round(width);
  30131. height = Math.round(height);
  30132. }
  30133. if (this._texture.isCube) {
  30134. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30135. }
  30136. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30137. };
  30138. BaseTexture.prototype.releaseInternalTexture = function () {
  30139. if (this._texture) {
  30140. this._texture.dispose();
  30141. this._texture = null;
  30142. }
  30143. };
  30144. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30145. get: function () {
  30146. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30147. return null;
  30148. }
  30149. if (!this._texture._sphericalPolynomial) {
  30150. this._texture._sphericalPolynomial =
  30151. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30152. }
  30153. return this._texture._sphericalPolynomial;
  30154. },
  30155. set: function (value) {
  30156. if (this._texture) {
  30157. this._texture._sphericalPolynomial = value;
  30158. }
  30159. },
  30160. enumerable: true,
  30161. configurable: true
  30162. });
  30163. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30164. get: function () {
  30165. if (this._texture) {
  30166. return this._texture._lodTextureHigh;
  30167. }
  30168. return null;
  30169. },
  30170. enumerable: true,
  30171. configurable: true
  30172. });
  30173. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30174. get: function () {
  30175. if (this._texture) {
  30176. return this._texture._lodTextureMid;
  30177. }
  30178. return null;
  30179. },
  30180. enumerable: true,
  30181. configurable: true
  30182. });
  30183. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30184. get: function () {
  30185. if (this._texture) {
  30186. return this._texture._lodTextureLow;
  30187. }
  30188. return null;
  30189. },
  30190. enumerable: true,
  30191. configurable: true
  30192. });
  30193. BaseTexture.prototype.dispose = function () {
  30194. if (!this._scene) {
  30195. return;
  30196. }
  30197. // Animations
  30198. this._scene.stopAnimation(this);
  30199. // Remove from scene
  30200. this._scene._removePendingData(this);
  30201. var index = this._scene.textures.indexOf(this);
  30202. if (index >= 0) {
  30203. this._scene.textures.splice(index, 1);
  30204. }
  30205. if (this._texture === undefined) {
  30206. return;
  30207. }
  30208. // Release
  30209. this.releaseInternalTexture();
  30210. // Callback
  30211. this.onDisposeObservable.notifyObservers(this);
  30212. this.onDisposeObservable.clear();
  30213. };
  30214. BaseTexture.prototype.serialize = function () {
  30215. if (!this.name) {
  30216. return null;
  30217. }
  30218. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30219. // Animations
  30220. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30221. return serializationObject;
  30222. };
  30223. BaseTexture.WhenAllReady = function (textures, callback) {
  30224. var numRemaining = textures.length;
  30225. if (numRemaining === 0) {
  30226. callback();
  30227. return;
  30228. }
  30229. var _loop_1 = function () {
  30230. texture = textures[i];
  30231. if (texture.isReady()) {
  30232. if (--numRemaining === 0) {
  30233. callback();
  30234. }
  30235. }
  30236. else {
  30237. onLoadObservable = texture.onLoadObservable;
  30238. var onLoadCallback_1 = function () {
  30239. onLoadObservable.removeCallback(onLoadCallback_1);
  30240. if (--numRemaining === 0) {
  30241. callback();
  30242. }
  30243. };
  30244. onLoadObservable.add(onLoadCallback_1);
  30245. }
  30246. };
  30247. var texture, onLoadObservable;
  30248. for (var i = 0; i < textures.length; i++) {
  30249. _loop_1();
  30250. }
  30251. };
  30252. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30253. __decorate([
  30254. BABYLON.serialize()
  30255. ], BaseTexture.prototype, "name", void 0);
  30256. __decorate([
  30257. BABYLON.serialize("hasAlpha")
  30258. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30259. __decorate([
  30260. BABYLON.serialize()
  30261. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30262. __decorate([
  30263. BABYLON.serialize()
  30264. ], BaseTexture.prototype, "level", void 0);
  30265. __decorate([
  30266. BABYLON.serialize()
  30267. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30268. __decorate([
  30269. BABYLON.serialize("coordinatesMode")
  30270. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30271. __decorate([
  30272. BABYLON.serialize()
  30273. ], BaseTexture.prototype, "wrapU", void 0);
  30274. __decorate([
  30275. BABYLON.serialize()
  30276. ], BaseTexture.prototype, "wrapV", void 0);
  30277. __decorate([
  30278. BABYLON.serialize()
  30279. ], BaseTexture.prototype, "wrapR", void 0);
  30280. __decorate([
  30281. BABYLON.serialize()
  30282. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30283. __decorate([
  30284. BABYLON.serialize()
  30285. ], BaseTexture.prototype, "isCube", void 0);
  30286. __decorate([
  30287. BABYLON.serialize()
  30288. ], BaseTexture.prototype, "is3D", void 0);
  30289. __decorate([
  30290. BABYLON.serialize()
  30291. ], BaseTexture.prototype, "gammaSpace", void 0);
  30292. __decorate([
  30293. BABYLON.serialize()
  30294. ], BaseTexture.prototype, "invertZ", void 0);
  30295. __decorate([
  30296. BABYLON.serialize()
  30297. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30298. __decorate([
  30299. BABYLON.serialize()
  30300. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30301. __decorate([
  30302. BABYLON.serialize()
  30303. ], BaseTexture.prototype, "lodGenerationScale", null);
  30304. __decorate([
  30305. BABYLON.serialize()
  30306. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30307. return BaseTexture;
  30308. }());
  30309. BABYLON.BaseTexture = BaseTexture;
  30310. })(BABYLON || (BABYLON = {}));
  30311. //# sourceMappingURL=babylon.baseTexture.js.map
  30312. var BABYLON;
  30313. (function (BABYLON) {
  30314. var Texture = /** @class */ (function (_super) {
  30315. __extends(Texture, _super);
  30316. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30317. if (noMipmap === void 0) { noMipmap = false; }
  30318. if (invertY === void 0) { invertY = true; }
  30319. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30320. if (onLoad === void 0) { onLoad = null; }
  30321. if (onError === void 0) { onError = null; }
  30322. if (buffer === void 0) { buffer = null; }
  30323. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30324. var _this = _super.call(this, scene) || this;
  30325. _this.uOffset = 0;
  30326. _this.vOffset = 0;
  30327. _this.uScale = 1.0;
  30328. _this.vScale = 1.0;
  30329. _this.uAng = 0;
  30330. _this.vAng = 0;
  30331. _this.wAng = 0;
  30332. /**
  30333. * Defines the center of rotation (U)
  30334. */
  30335. _this.uRotationCenter = 0.5;
  30336. /**
  30337. * Defines the center of rotation (V)
  30338. */
  30339. _this.vRotationCenter = 0.5;
  30340. /**
  30341. * Defines the center of rotation (W)
  30342. */
  30343. _this.wRotationCenter = 0.5;
  30344. _this._isBlocking = true;
  30345. _this.name = url || "";
  30346. _this.url = url;
  30347. _this._noMipmap = noMipmap;
  30348. _this._invertY = invertY;
  30349. _this._samplingMode = samplingMode;
  30350. _this._buffer = buffer;
  30351. _this._deleteBuffer = deleteBuffer;
  30352. if (format) {
  30353. _this._format = format;
  30354. }
  30355. scene = _this.getScene();
  30356. if (!scene) {
  30357. return _this;
  30358. }
  30359. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30360. var load = function () {
  30361. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30362. _this.onLoadObservable.notifyObservers(_this);
  30363. }
  30364. if (onLoad) {
  30365. onLoad();
  30366. }
  30367. if (!_this.isBlocking && scene) {
  30368. scene.resetCachedMaterial();
  30369. }
  30370. };
  30371. if (!_this.url) {
  30372. _this._delayedOnLoad = load;
  30373. _this._delayedOnError = onError;
  30374. return _this;
  30375. }
  30376. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30377. if (!_this._texture) {
  30378. if (!scene.useDelayedTextureLoading) {
  30379. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30380. if (deleteBuffer) {
  30381. delete _this._buffer;
  30382. }
  30383. }
  30384. else {
  30385. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30386. _this._delayedOnLoad = load;
  30387. _this._delayedOnError = onError;
  30388. }
  30389. }
  30390. else {
  30391. if (_this._texture.isReady) {
  30392. BABYLON.Tools.SetImmediate(function () { return load(); });
  30393. }
  30394. else {
  30395. _this._texture.onLoadedObservable.add(load);
  30396. }
  30397. }
  30398. return _this;
  30399. }
  30400. Object.defineProperty(Texture.prototype, "noMipmap", {
  30401. get: function () {
  30402. return this._noMipmap;
  30403. },
  30404. enumerable: true,
  30405. configurable: true
  30406. });
  30407. Object.defineProperty(Texture.prototype, "isBlocking", {
  30408. get: function () {
  30409. return this._isBlocking;
  30410. },
  30411. set: function (value) {
  30412. this._isBlocking = value;
  30413. },
  30414. enumerable: true,
  30415. configurable: true
  30416. });
  30417. Object.defineProperty(Texture.prototype, "samplingMode", {
  30418. get: function () {
  30419. return this._samplingMode;
  30420. },
  30421. enumerable: true,
  30422. configurable: true
  30423. });
  30424. /**
  30425. * Update the url (and optional buffer) of this texture if url was null during construction.
  30426. * @param url the url of the texture
  30427. * @param buffer the buffer of the texture (defaults to null)
  30428. */
  30429. Texture.prototype.updateURL = function (url, buffer) {
  30430. if (buffer === void 0) { buffer = null; }
  30431. if (this.url) {
  30432. throw new Error("URL is already set");
  30433. }
  30434. this.url = url;
  30435. this._buffer = buffer;
  30436. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30437. this.delayLoad();
  30438. };
  30439. Texture.prototype.delayLoad = function () {
  30440. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30441. return;
  30442. }
  30443. var scene = this.getScene();
  30444. if (!scene) {
  30445. return;
  30446. }
  30447. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30448. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30449. if (!this._texture) {
  30450. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30451. if (this._deleteBuffer) {
  30452. delete this._buffer;
  30453. }
  30454. }
  30455. else {
  30456. if (this._delayedOnLoad) {
  30457. if (this._texture.isReady) {
  30458. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30459. }
  30460. else {
  30461. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30462. }
  30463. }
  30464. }
  30465. this._delayedOnLoad = null;
  30466. this._delayedOnError = null;
  30467. };
  30468. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30469. if (!this._texture) {
  30470. return;
  30471. }
  30472. var scene = this.getScene();
  30473. if (!scene) {
  30474. return;
  30475. }
  30476. this._samplingMode = samplingMode;
  30477. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30478. };
  30479. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30480. x *= this.uScale;
  30481. y *= this.vScale;
  30482. x -= this.uRotationCenter * this.uScale;
  30483. y -= this.vRotationCenter * this.vScale;
  30484. z -= this.wRotationCenter;
  30485. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30486. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30487. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30488. t.z += this.wRotationCenter;
  30489. };
  30490. Texture.prototype.getTextureMatrix = function () {
  30491. var _this = this;
  30492. if (this.uOffset === this._cachedUOffset &&
  30493. this.vOffset === this._cachedVOffset &&
  30494. this.uScale === this._cachedUScale &&
  30495. this.vScale === this._cachedVScale &&
  30496. this.uAng === this._cachedUAng &&
  30497. this.vAng === this._cachedVAng &&
  30498. this.wAng === this._cachedWAng) {
  30499. return this._cachedTextureMatrix;
  30500. }
  30501. this._cachedUOffset = this.uOffset;
  30502. this._cachedVOffset = this.vOffset;
  30503. this._cachedUScale = this.uScale;
  30504. this._cachedVScale = this.vScale;
  30505. this._cachedUAng = this.uAng;
  30506. this._cachedVAng = this.vAng;
  30507. this._cachedWAng = this.wAng;
  30508. if (!this._cachedTextureMatrix) {
  30509. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30510. this._rowGenerationMatrix = new BABYLON.Matrix();
  30511. this._t0 = BABYLON.Vector3.Zero();
  30512. this._t1 = BABYLON.Vector3.Zero();
  30513. this._t2 = BABYLON.Vector3.Zero();
  30514. }
  30515. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30516. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30517. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30518. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30519. this._t1.subtractInPlace(this._t0);
  30520. this._t2.subtractInPlace(this._t0);
  30521. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30522. this._cachedTextureMatrix.m[0] = this._t1.x;
  30523. this._cachedTextureMatrix.m[1] = this._t1.y;
  30524. this._cachedTextureMatrix.m[2] = this._t1.z;
  30525. this._cachedTextureMatrix.m[4] = this._t2.x;
  30526. this._cachedTextureMatrix.m[5] = this._t2.y;
  30527. this._cachedTextureMatrix.m[6] = this._t2.z;
  30528. this._cachedTextureMatrix.m[8] = this._t0.x;
  30529. this._cachedTextureMatrix.m[9] = this._t0.y;
  30530. this._cachedTextureMatrix.m[10] = this._t0.z;
  30531. var scene = this.getScene();
  30532. if (!scene) {
  30533. return this._cachedTextureMatrix;
  30534. }
  30535. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30536. return mat.hasTexture(_this);
  30537. });
  30538. return this._cachedTextureMatrix;
  30539. };
  30540. Texture.prototype.getReflectionTextureMatrix = function () {
  30541. var _this = this;
  30542. var scene = this.getScene();
  30543. if (!scene) {
  30544. return this._cachedTextureMatrix;
  30545. }
  30546. if (this.uOffset === this._cachedUOffset &&
  30547. this.vOffset === this._cachedVOffset &&
  30548. this.uScale === this._cachedUScale &&
  30549. this.vScale === this._cachedVScale &&
  30550. this.coordinatesMode === this._cachedCoordinatesMode) {
  30551. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30552. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30553. return this._cachedTextureMatrix;
  30554. }
  30555. }
  30556. else {
  30557. return this._cachedTextureMatrix;
  30558. }
  30559. }
  30560. if (!this._cachedTextureMatrix) {
  30561. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30562. }
  30563. if (!this._projectionModeMatrix) {
  30564. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30565. }
  30566. this._cachedUOffset = this.uOffset;
  30567. this._cachedVOffset = this.vOffset;
  30568. this._cachedUScale = this.uScale;
  30569. this._cachedVScale = this.vScale;
  30570. this._cachedCoordinatesMode = this.coordinatesMode;
  30571. switch (this.coordinatesMode) {
  30572. case Texture.PLANAR_MODE:
  30573. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30574. this._cachedTextureMatrix[0] = this.uScale;
  30575. this._cachedTextureMatrix[5] = this.vScale;
  30576. this._cachedTextureMatrix[12] = this.uOffset;
  30577. this._cachedTextureMatrix[13] = this.vOffset;
  30578. break;
  30579. case Texture.PROJECTION_MODE:
  30580. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30581. this._projectionModeMatrix.m[0] = 0.5;
  30582. this._projectionModeMatrix.m[5] = -0.5;
  30583. this._projectionModeMatrix.m[10] = 0.0;
  30584. this._projectionModeMatrix.m[12] = 0.5;
  30585. this._projectionModeMatrix.m[13] = 0.5;
  30586. this._projectionModeMatrix.m[14] = 1.0;
  30587. this._projectionModeMatrix.m[15] = 1.0;
  30588. var projectionMatrix = scene.getProjectionMatrix();
  30589. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30590. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30591. break;
  30592. default:
  30593. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30594. break;
  30595. }
  30596. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30597. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30598. });
  30599. return this._cachedTextureMatrix;
  30600. };
  30601. Texture.prototype.clone = function () {
  30602. var _this = this;
  30603. return BABYLON.SerializationHelper.Clone(function () {
  30604. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30605. }, this);
  30606. };
  30607. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30608. get: function () {
  30609. if (!this._onLoadObservable) {
  30610. this._onLoadObservable = new BABYLON.Observable();
  30611. }
  30612. return this._onLoadObservable;
  30613. },
  30614. enumerable: true,
  30615. configurable: true
  30616. });
  30617. Texture.prototype.serialize = function () {
  30618. var serializationObject = _super.prototype.serialize.call(this);
  30619. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30620. serializationObject.base64String = this._buffer;
  30621. serializationObject.name = serializationObject.name.replace("data:", "");
  30622. }
  30623. serializationObject.invertY = this._invertY;
  30624. serializationObject.samplingMode = this.samplingMode;
  30625. return serializationObject;
  30626. };
  30627. Texture.prototype.getClassName = function () {
  30628. return "Texture";
  30629. };
  30630. Texture.prototype.dispose = function () {
  30631. _super.prototype.dispose.call(this);
  30632. if (this._onLoadObservable) {
  30633. this._onLoadObservable.clear();
  30634. this._onLoadObservable = null;
  30635. }
  30636. this._delayedOnLoad = null;
  30637. this._delayedOnError = null;
  30638. };
  30639. // Statics
  30640. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30641. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30642. if (onLoad === void 0) { onLoad = null; }
  30643. if (onError === void 0) { onError = null; }
  30644. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30645. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30646. };
  30647. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30648. if (parsedTexture.customType) {
  30649. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30650. // Update Sampling Mode
  30651. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30652. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30653. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30654. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30655. }
  30656. }
  30657. return parsedCustomTexture;
  30658. }
  30659. if (parsedTexture.isCube) {
  30660. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30661. }
  30662. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30663. return null;
  30664. }
  30665. var texture = BABYLON.SerializationHelper.Parse(function () {
  30666. var generateMipMaps = true;
  30667. if (parsedTexture.noMipmap) {
  30668. generateMipMaps = false;
  30669. }
  30670. if (parsedTexture.mirrorPlane) {
  30671. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30672. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30673. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30674. return mirrorTexture;
  30675. }
  30676. else if (parsedTexture.isRenderTarget) {
  30677. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30678. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30679. return renderTargetTexture;
  30680. }
  30681. else {
  30682. var texture;
  30683. if (parsedTexture.base64String) {
  30684. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30685. }
  30686. else {
  30687. var url = rootUrl + parsedTexture.name;
  30688. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30689. url = parsedTexture.url;
  30690. }
  30691. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30692. }
  30693. return texture;
  30694. }
  30695. }, parsedTexture, scene);
  30696. // Update Sampling Mode
  30697. if (parsedTexture.samplingMode) {
  30698. var sampling = parsedTexture.samplingMode;
  30699. if (texture._samplingMode !== sampling) {
  30700. texture.updateSamplingMode(sampling);
  30701. }
  30702. }
  30703. // Animations
  30704. if (parsedTexture.animations) {
  30705. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30706. var parsedAnimation = parsedTexture.animations[animationIndex];
  30707. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30708. }
  30709. }
  30710. return texture;
  30711. };
  30712. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30713. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30714. if (noMipmap === void 0) { noMipmap = false; }
  30715. if (invertY === void 0) { invertY = true; }
  30716. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30717. if (onLoad === void 0) { onLoad = null; }
  30718. if (onError === void 0) { onError = null; }
  30719. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30720. if (name.substr(0, 5) !== "data:") {
  30721. name = "data:" + name;
  30722. }
  30723. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30724. };
  30725. // Constants
  30726. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30727. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30728. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30729. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30730. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30731. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30732. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30733. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30734. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30735. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30736. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30737. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30738. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30739. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30740. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30741. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30742. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30743. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30744. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30745. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30746. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30747. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30748. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30749. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30750. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30751. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30752. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30753. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30754. /**
  30755. * 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
  30756. */
  30757. Texture.UseSerializedUrlIfAny = false;
  30758. __decorate([
  30759. BABYLON.serialize()
  30760. ], Texture.prototype, "url", void 0);
  30761. __decorate([
  30762. BABYLON.serialize()
  30763. ], Texture.prototype, "uOffset", void 0);
  30764. __decorate([
  30765. BABYLON.serialize()
  30766. ], Texture.prototype, "vOffset", void 0);
  30767. __decorate([
  30768. BABYLON.serialize()
  30769. ], Texture.prototype, "uScale", void 0);
  30770. __decorate([
  30771. BABYLON.serialize()
  30772. ], Texture.prototype, "vScale", void 0);
  30773. __decorate([
  30774. BABYLON.serialize()
  30775. ], Texture.prototype, "uAng", void 0);
  30776. __decorate([
  30777. BABYLON.serialize()
  30778. ], Texture.prototype, "vAng", void 0);
  30779. __decorate([
  30780. BABYLON.serialize()
  30781. ], Texture.prototype, "wAng", void 0);
  30782. __decorate([
  30783. BABYLON.serialize()
  30784. ], Texture.prototype, "uRotationCenter", void 0);
  30785. __decorate([
  30786. BABYLON.serialize()
  30787. ], Texture.prototype, "vRotationCenter", void 0);
  30788. __decorate([
  30789. BABYLON.serialize()
  30790. ], Texture.prototype, "wRotationCenter", void 0);
  30791. __decorate([
  30792. BABYLON.serialize()
  30793. ], Texture.prototype, "isBlocking", null);
  30794. return Texture;
  30795. }(BABYLON.BaseTexture));
  30796. BABYLON.Texture = Texture;
  30797. })(BABYLON || (BABYLON = {}));
  30798. //# sourceMappingURL=babylon.texture.js.map
  30799. var BABYLON;
  30800. (function (BABYLON) {
  30801. /**
  30802. * @hidden
  30803. **/
  30804. var _InstancesBatch = /** @class */ (function () {
  30805. function _InstancesBatch() {
  30806. this.mustReturn = false;
  30807. this.visibleInstances = new Array();
  30808. this.renderSelf = new Array();
  30809. }
  30810. return _InstancesBatch;
  30811. }());
  30812. BABYLON._InstancesBatch = _InstancesBatch;
  30813. var Mesh = /** @class */ (function (_super) {
  30814. __extends(Mesh, _super);
  30815. /**
  30816. * @constructor
  30817. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30818. * @param {Scene} scene The scene to add this mesh to.
  30819. * @param {Node} parent The parent of this mesh, if it has one
  30820. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30821. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30822. * When false, achieved by calling a clone(), also passing False.
  30823. * This will make creation of children, recursive.
  30824. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30825. */
  30826. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30827. if (scene === void 0) { scene = null; }
  30828. if (parent === void 0) { parent = null; }
  30829. if (source === void 0) { source = null; }
  30830. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30831. var _this = _super.call(this, name, scene) || this;
  30832. // Events
  30833. /**
  30834. * An event triggered before rendering the mesh
  30835. */
  30836. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30837. /**
  30838. * An event triggered after rendering the mesh
  30839. */
  30840. _this.onAfterRenderObservable = new BABYLON.Observable();
  30841. /**
  30842. * An event triggered before drawing the mesh
  30843. */
  30844. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30845. // Members
  30846. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30847. _this.instances = new Array();
  30848. _this._LODLevels = new Array();
  30849. _this._visibleInstances = {};
  30850. _this._renderIdForInstances = new Array();
  30851. _this._batchCache = new _InstancesBatch();
  30852. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30853. // Use by builder only to know what orientation were the mesh build in.
  30854. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30855. _this.overrideMaterialSideOrientation = null;
  30856. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30857. // Will be used to save a source mesh reference, If any
  30858. _this._source = null;
  30859. scene = _this.getScene();
  30860. if (source) {
  30861. // Geometry
  30862. if (source._geometry) {
  30863. source._geometry.applyToMesh(_this);
  30864. }
  30865. // Deep copy
  30866. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30867. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  30868. // Source mesh
  30869. _this._source = source;
  30870. // Metadata
  30871. if (source.metadata && source.metadata.clone) {
  30872. _this.metadata = source.metadata.clone();
  30873. }
  30874. else {
  30875. _this.metadata = source.metadata;
  30876. }
  30877. // Tags
  30878. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30879. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30880. }
  30881. // Parent
  30882. _this.parent = source.parent;
  30883. // Pivot
  30884. _this.setPivotMatrix(source.getPivotMatrix());
  30885. _this.id = name + "." + source.id;
  30886. // Material
  30887. _this.material = source.material;
  30888. var index;
  30889. if (!doNotCloneChildren) {
  30890. // Children
  30891. var directDescendants = source.getDescendants(true);
  30892. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30893. var child = directDescendants[index_1];
  30894. if (child.clone) {
  30895. child.clone(name + "." + child.name, _this);
  30896. }
  30897. }
  30898. }
  30899. // Physics clone
  30900. var physicsEngine = _this.getScene().getPhysicsEngine();
  30901. if (clonePhysicsImpostor && physicsEngine) {
  30902. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30903. if (impostor) {
  30904. _this.physicsImpostor = impostor.clone(_this);
  30905. }
  30906. }
  30907. // Particles
  30908. for (index = 0; index < scene.particleSystems.length; index++) {
  30909. var system = scene.particleSystems[index];
  30910. if (system.emitter === source) {
  30911. system.clone(system.name, _this);
  30912. }
  30913. }
  30914. _this.refreshBoundingInfo();
  30915. _this.computeWorldMatrix(true);
  30916. }
  30917. // Parent
  30918. if (parent !== null) {
  30919. _this.parent = parent;
  30920. }
  30921. return _this;
  30922. }
  30923. Object.defineProperty(Mesh, "FRONTSIDE", {
  30924. /**
  30925. * Mesh side orientation : usually the external or front surface
  30926. */
  30927. get: function () {
  30928. return Mesh._FRONTSIDE;
  30929. },
  30930. enumerable: true,
  30931. configurable: true
  30932. });
  30933. Object.defineProperty(Mesh, "BACKSIDE", {
  30934. /**
  30935. * Mesh side orientation : usually the internal or back surface
  30936. */
  30937. get: function () {
  30938. return Mesh._BACKSIDE;
  30939. },
  30940. enumerable: true,
  30941. configurable: true
  30942. });
  30943. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30944. /**
  30945. * Mesh side orientation : both internal and external or front and back surfaces
  30946. */
  30947. get: function () {
  30948. return Mesh._DOUBLESIDE;
  30949. },
  30950. enumerable: true,
  30951. configurable: true
  30952. });
  30953. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30954. /**
  30955. * Mesh side orientation : by default, `FRONTSIDE`
  30956. */
  30957. get: function () {
  30958. return Mesh._DEFAULTSIDE;
  30959. },
  30960. enumerable: true,
  30961. configurable: true
  30962. });
  30963. Object.defineProperty(Mesh, "NO_CAP", {
  30964. /**
  30965. * Mesh cap setting : no cap
  30966. */
  30967. get: function () {
  30968. return Mesh._NO_CAP;
  30969. },
  30970. enumerable: true,
  30971. configurable: true
  30972. });
  30973. Object.defineProperty(Mesh, "CAP_START", {
  30974. /**
  30975. * Mesh cap setting : one cap at the beginning of the mesh
  30976. */
  30977. get: function () {
  30978. return Mesh._CAP_START;
  30979. },
  30980. enumerable: true,
  30981. configurable: true
  30982. });
  30983. Object.defineProperty(Mesh, "CAP_END", {
  30984. /**
  30985. * Mesh cap setting : one cap at the end of the mesh
  30986. */
  30987. get: function () {
  30988. return Mesh._CAP_END;
  30989. },
  30990. enumerable: true,
  30991. configurable: true
  30992. });
  30993. Object.defineProperty(Mesh, "CAP_ALL", {
  30994. /**
  30995. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30996. */
  30997. get: function () {
  30998. return Mesh._CAP_ALL;
  30999. },
  31000. enumerable: true,
  31001. configurable: true
  31002. });
  31003. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31004. set: function (callback) {
  31005. if (this._onBeforeDrawObserver) {
  31006. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31007. }
  31008. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31009. },
  31010. enumerable: true,
  31011. configurable: true
  31012. });
  31013. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31014. get: function () {
  31015. return this._morphTargetManager;
  31016. },
  31017. set: function (value) {
  31018. if (this._morphTargetManager === value) {
  31019. return;
  31020. }
  31021. this._morphTargetManager = value;
  31022. this._syncGeometryWithMorphTargetManager();
  31023. },
  31024. enumerable: true,
  31025. configurable: true
  31026. });
  31027. Object.defineProperty(Mesh.prototype, "source", {
  31028. get: function () {
  31029. return this._source;
  31030. },
  31031. enumerable: true,
  31032. configurable: true
  31033. });
  31034. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31035. get: function () {
  31036. return this._unIndexed;
  31037. },
  31038. set: function (value) {
  31039. if (this._unIndexed !== value) {
  31040. this._unIndexed = value;
  31041. this._markSubMeshesAsAttributesDirty();
  31042. }
  31043. },
  31044. enumerable: true,
  31045. configurable: true
  31046. });
  31047. // Methods
  31048. /**
  31049. * Returns the string "Mesh".
  31050. */
  31051. Mesh.prototype.getClassName = function () {
  31052. return "Mesh";
  31053. };
  31054. /**
  31055. * Returns a string.
  31056. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31057. */
  31058. Mesh.prototype.toString = function (fullDetails) {
  31059. var ret = _super.prototype.toString.call(this, fullDetails);
  31060. ret += ", n vertices: " + this.getTotalVertices();
  31061. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31062. if (this.animations) {
  31063. for (var i = 0; i < this.animations.length; i++) {
  31064. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31065. }
  31066. }
  31067. if (fullDetails) {
  31068. if (this._geometry) {
  31069. var ib = this.getIndices();
  31070. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31071. if (vb && ib) {
  31072. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31073. }
  31074. }
  31075. else {
  31076. ret += ", flat shading: UNKNOWN";
  31077. }
  31078. }
  31079. return ret;
  31080. };
  31081. Mesh.prototype._unBindEffect = function () {
  31082. _super.prototype._unBindEffect.call(this);
  31083. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31084. var instance = _a[_i];
  31085. instance._unBindEffect();
  31086. }
  31087. };
  31088. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31089. /**
  31090. * True if the mesh has some Levels Of Details (LOD).
  31091. * Returns a boolean.
  31092. */
  31093. get: function () {
  31094. return this._LODLevels.length > 0;
  31095. },
  31096. enumerable: true,
  31097. configurable: true
  31098. });
  31099. /**
  31100. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31101. * @returns an array of {BABYLON.MeshLODLevel}
  31102. */
  31103. Mesh.prototype.getLODLevels = function () {
  31104. return this._LODLevels;
  31105. };
  31106. Mesh.prototype._sortLODLevels = function () {
  31107. this._LODLevels.sort(function (a, b) {
  31108. if (a.distance < b.distance) {
  31109. return 1;
  31110. }
  31111. if (a.distance > b.distance) {
  31112. return -1;
  31113. }
  31114. return 0;
  31115. });
  31116. };
  31117. /**
  31118. * Add a mesh as LOD level triggered at the given distance.
  31119. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31120. * @param distance The distance from the center of the object to show this level
  31121. * @param mesh The mesh to be added as LOD level (can be null)
  31122. * @return This mesh (for chaining)
  31123. */
  31124. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31125. if (mesh && mesh._masterMesh) {
  31126. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31127. return this;
  31128. }
  31129. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31130. this._LODLevels.push(level);
  31131. if (mesh) {
  31132. mesh._masterMesh = this;
  31133. }
  31134. this._sortLODLevels();
  31135. return this;
  31136. };
  31137. /**
  31138. * Returns the LOD level mesh at the passed distance or null if not found.
  31139. * It is related to the method `addLODLevel(distance, mesh)`.
  31140. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31141. * Returns an object Mesh or `null`.
  31142. */
  31143. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31144. for (var index = 0; index < this._LODLevels.length; index++) {
  31145. var level = this._LODLevels[index];
  31146. if (level.distance === distance) {
  31147. return level.mesh;
  31148. }
  31149. }
  31150. return null;
  31151. };
  31152. /**
  31153. * Remove a mesh from the LOD array
  31154. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31155. * @param {Mesh} mesh The mesh to be removed.
  31156. * @return {Mesh} This mesh (for chaining)
  31157. */
  31158. Mesh.prototype.removeLODLevel = function (mesh) {
  31159. for (var index = 0; index < this._LODLevels.length; index++) {
  31160. if (this._LODLevels[index].mesh === mesh) {
  31161. this._LODLevels.splice(index, 1);
  31162. if (mesh) {
  31163. mesh._masterMesh = null;
  31164. }
  31165. }
  31166. }
  31167. this._sortLODLevels();
  31168. return this;
  31169. };
  31170. /**
  31171. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31172. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31173. */
  31174. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31175. if (!this._LODLevels || this._LODLevels.length === 0) {
  31176. return this;
  31177. }
  31178. var bSphere;
  31179. if (boundingSphere) {
  31180. bSphere = boundingSphere;
  31181. }
  31182. else {
  31183. var boundingInfo = this.getBoundingInfo();
  31184. bSphere = boundingInfo.boundingSphere;
  31185. }
  31186. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31187. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31188. if (this.onLODLevelSelection) {
  31189. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31190. }
  31191. return this;
  31192. }
  31193. for (var index = 0; index < this._LODLevels.length; index++) {
  31194. var level = this._LODLevels[index];
  31195. if (level.distance < distanceToCamera) {
  31196. if (level.mesh) {
  31197. level.mesh._preActivate();
  31198. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31199. }
  31200. if (this.onLODLevelSelection) {
  31201. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31202. }
  31203. return level.mesh;
  31204. }
  31205. }
  31206. if (this.onLODLevelSelection) {
  31207. this.onLODLevelSelection(distanceToCamera, this, this);
  31208. }
  31209. return this;
  31210. };
  31211. Object.defineProperty(Mesh.prototype, "geometry", {
  31212. /**
  31213. * Returns the mesh internal Geometry object.
  31214. */
  31215. get: function () {
  31216. return this._geometry;
  31217. },
  31218. enumerable: true,
  31219. configurable: true
  31220. });
  31221. /**
  31222. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31223. */
  31224. Mesh.prototype.getTotalVertices = function () {
  31225. if (this._geometry === null || this._geometry === undefined) {
  31226. return 0;
  31227. }
  31228. return this._geometry.getTotalVertices();
  31229. };
  31230. /**
  31231. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31232. * 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.
  31233. * You can force the copy with forceCopy === true
  31234. * Returns null if the mesh has no geometry or no vertex buffer.
  31235. * Possible `kind` values :
  31236. * - BABYLON.VertexBuffer.PositionKind
  31237. * - BABYLON.VertexBuffer.UVKind
  31238. * - BABYLON.VertexBuffer.UV2Kind
  31239. * - BABYLON.VertexBuffer.UV3Kind
  31240. * - BABYLON.VertexBuffer.UV4Kind
  31241. * - BABYLON.VertexBuffer.UV5Kind
  31242. * - BABYLON.VertexBuffer.UV6Kind
  31243. * - BABYLON.VertexBuffer.ColorKind
  31244. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31245. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31246. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31247. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31248. */
  31249. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31250. if (!this._geometry) {
  31251. return null;
  31252. }
  31253. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31254. };
  31255. /**
  31256. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31257. * Returns `null` if the mesh has no geometry.
  31258. * Possible `kind` values :
  31259. * - BABYLON.VertexBuffer.PositionKind
  31260. * - BABYLON.VertexBuffer.UVKind
  31261. * - BABYLON.VertexBuffer.UV2Kind
  31262. * - BABYLON.VertexBuffer.UV3Kind
  31263. * - BABYLON.VertexBuffer.UV4Kind
  31264. * - BABYLON.VertexBuffer.UV5Kind
  31265. * - BABYLON.VertexBuffer.UV6Kind
  31266. * - BABYLON.VertexBuffer.ColorKind
  31267. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31268. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31269. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31270. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31271. */
  31272. Mesh.prototype.getVertexBuffer = function (kind) {
  31273. if (!this._geometry) {
  31274. return null;
  31275. }
  31276. return this._geometry.getVertexBuffer(kind);
  31277. };
  31278. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31279. if (!this._geometry) {
  31280. if (this._delayInfo) {
  31281. return this._delayInfo.indexOf(kind) !== -1;
  31282. }
  31283. return false;
  31284. }
  31285. return this._geometry.isVerticesDataPresent(kind);
  31286. };
  31287. /**
  31288. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31289. * Possible `kind` values :
  31290. * - BABYLON.VertexBuffer.PositionKind
  31291. * - BABYLON.VertexBuffer.UVKind
  31292. * - BABYLON.VertexBuffer.UV2Kind
  31293. * - BABYLON.VertexBuffer.UV3Kind
  31294. * - BABYLON.VertexBuffer.UV4Kind
  31295. * - BABYLON.VertexBuffer.UV5Kind
  31296. * - BABYLON.VertexBuffer.UV6Kind
  31297. * - BABYLON.VertexBuffer.ColorKind
  31298. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31299. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31300. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31301. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31302. */
  31303. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31304. if (!this._geometry) {
  31305. if (this._delayInfo) {
  31306. return this._delayInfo.indexOf(kind) !== -1;
  31307. }
  31308. return false;
  31309. }
  31310. return this._geometry.isVertexBufferUpdatable(kind);
  31311. };
  31312. /**
  31313. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31314. * Possible `kind` values :
  31315. * - BABYLON.VertexBuffer.PositionKind
  31316. * - BABYLON.VertexBuffer.UVKind
  31317. * - BABYLON.VertexBuffer.UV2Kind
  31318. * - BABYLON.VertexBuffer.UV3Kind
  31319. * - BABYLON.VertexBuffer.UV4Kind
  31320. * - BABYLON.VertexBuffer.UV5Kind
  31321. * - BABYLON.VertexBuffer.UV6Kind
  31322. * - BABYLON.VertexBuffer.ColorKind
  31323. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31324. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31325. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31326. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31327. */
  31328. Mesh.prototype.getVerticesDataKinds = function () {
  31329. if (!this._geometry) {
  31330. var result = new Array();
  31331. if (this._delayInfo) {
  31332. this._delayInfo.forEach(function (kind, index, array) {
  31333. result.push(kind);
  31334. });
  31335. }
  31336. return result;
  31337. }
  31338. return this._geometry.getVerticesDataKinds();
  31339. };
  31340. /**
  31341. * Returns a positive integer : the total number of indices in this mesh geometry.
  31342. * Returns zero if the mesh has no geometry.
  31343. */
  31344. Mesh.prototype.getTotalIndices = function () {
  31345. if (!this._geometry) {
  31346. return 0;
  31347. }
  31348. return this._geometry.getTotalIndices();
  31349. };
  31350. /**
  31351. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31352. * 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.
  31353. * Returns an empty array if the mesh has no geometry.
  31354. */
  31355. Mesh.prototype.getIndices = function (copyWhenShared) {
  31356. if (!this._geometry) {
  31357. return [];
  31358. }
  31359. return this._geometry.getIndices(copyWhenShared);
  31360. };
  31361. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31362. get: function () {
  31363. return this._masterMesh !== null && this._masterMesh !== undefined;
  31364. },
  31365. enumerable: true,
  31366. configurable: true
  31367. });
  31368. /**
  31369. * Determine if the current mesh is ready to be rendered
  31370. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31371. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31372. * @returns true if all associated assets are ready (material, textures, shaders)
  31373. */
  31374. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31375. if (completeCheck === void 0) { completeCheck = false; }
  31376. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31377. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31378. return false;
  31379. }
  31380. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31381. return false;
  31382. }
  31383. if (!this.subMeshes || this.subMeshes.length === 0) {
  31384. return true;
  31385. }
  31386. if (!completeCheck) {
  31387. return true;
  31388. }
  31389. var engine = this.getEngine();
  31390. var scene = this.getScene();
  31391. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31392. this.computeWorldMatrix();
  31393. var mat = this.material || scene.defaultMaterial;
  31394. if (mat) {
  31395. if (mat.storeEffectOnSubMeshes) {
  31396. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31397. var subMesh = _a[_i];
  31398. var effectiveMaterial = subMesh.getMaterial();
  31399. if (effectiveMaterial) {
  31400. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31401. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31402. return false;
  31403. }
  31404. }
  31405. else {
  31406. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31407. return false;
  31408. }
  31409. }
  31410. }
  31411. }
  31412. }
  31413. else {
  31414. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31415. return false;
  31416. }
  31417. }
  31418. }
  31419. // Shadows
  31420. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31421. var light = _c[_b];
  31422. var generator = light.getShadowGenerator();
  31423. if (generator) {
  31424. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31425. var subMesh = _e[_d];
  31426. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31427. return false;
  31428. }
  31429. }
  31430. }
  31431. }
  31432. // LOD
  31433. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31434. var lod = _g[_f];
  31435. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31436. return false;
  31437. }
  31438. }
  31439. return true;
  31440. };
  31441. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31442. /**
  31443. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31444. * This property is pertinent only for updatable parametric shapes.
  31445. */
  31446. get: function () {
  31447. return this._areNormalsFrozen;
  31448. },
  31449. enumerable: true,
  31450. configurable: true
  31451. });
  31452. /**
  31453. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31454. * It has no effect at all on other shapes.
  31455. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31456. * Returns the Mesh.
  31457. */
  31458. Mesh.prototype.freezeNormals = function () {
  31459. this._areNormalsFrozen = true;
  31460. return this;
  31461. };
  31462. /**
  31463. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31464. * It has no effect at all on other shapes.
  31465. * It reactivates the mesh normals computation if it was previously frozen.
  31466. * Returns the Mesh.
  31467. */
  31468. Mesh.prototype.unfreezeNormals = function () {
  31469. this._areNormalsFrozen = false;
  31470. return this;
  31471. };
  31472. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31473. /**
  31474. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31475. */
  31476. set: function (count) {
  31477. this._overridenInstanceCount = count;
  31478. },
  31479. enumerable: true,
  31480. configurable: true
  31481. });
  31482. // Methods
  31483. Mesh.prototype._preActivate = function () {
  31484. var sceneRenderId = this.getScene().getRenderId();
  31485. if (this._preActivateId === sceneRenderId) {
  31486. return this;
  31487. }
  31488. this._preActivateId = sceneRenderId;
  31489. this._visibleInstances = null;
  31490. return this;
  31491. };
  31492. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31493. if (this._visibleInstances) {
  31494. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31495. }
  31496. return this;
  31497. };
  31498. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31499. if (!this._visibleInstances) {
  31500. this._visibleInstances = {};
  31501. this._visibleInstances.defaultRenderId = renderId;
  31502. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31503. }
  31504. if (!this._visibleInstances[renderId]) {
  31505. this._visibleInstances[renderId] = new Array();
  31506. }
  31507. this._visibleInstances[renderId].push(instance);
  31508. return this;
  31509. };
  31510. /**
  31511. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31512. * This means the mesh underlying bounding box and sphere are recomputed.
  31513. * Returns the Mesh.
  31514. */
  31515. Mesh.prototype.refreshBoundingInfo = function () {
  31516. return this._refreshBoundingInfo(false);
  31517. };
  31518. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31519. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31520. return this;
  31521. }
  31522. var data = this._getPositionData(applySkeleton);
  31523. if (data) {
  31524. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31525. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31526. }
  31527. if (this.subMeshes) {
  31528. for (var index = 0; index < this.subMeshes.length; index++) {
  31529. this.subMeshes[index].refreshBoundingInfo();
  31530. }
  31531. }
  31532. this._updateBoundingInfo();
  31533. return this;
  31534. };
  31535. Mesh.prototype._getPositionData = function (applySkeleton) {
  31536. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31537. if (data && applySkeleton && this.skeleton) {
  31538. data = BABYLON.Tools.Slice(data);
  31539. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31540. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31541. if (matricesWeightsData && matricesIndicesData) {
  31542. var needExtras = this.numBoneInfluencers > 4;
  31543. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31544. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31545. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31546. var tempVector = BABYLON.Tmp.Vector3[0];
  31547. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31548. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31549. var matWeightIdx = 0;
  31550. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31551. finalMatrix.reset();
  31552. var inf;
  31553. var weight;
  31554. for (inf = 0; inf < 4; inf++) {
  31555. weight = matricesWeightsData[matWeightIdx + inf];
  31556. if (weight > 0) {
  31557. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31558. finalMatrix.addToSelf(tempMatrix);
  31559. }
  31560. }
  31561. if (needExtras) {
  31562. for (inf = 0; inf < 4; inf++) {
  31563. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31564. if (weight > 0) {
  31565. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31566. finalMatrix.addToSelf(tempMatrix);
  31567. }
  31568. }
  31569. }
  31570. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31571. tempVector.toArray(data, index);
  31572. }
  31573. }
  31574. }
  31575. return data;
  31576. };
  31577. Mesh.prototype._createGlobalSubMesh = function (force) {
  31578. var totalVertices = this.getTotalVertices();
  31579. if (!totalVertices || !this.getIndices()) {
  31580. return null;
  31581. }
  31582. // Check if we need to recreate the submeshes
  31583. if (this.subMeshes && this.subMeshes.length > 0) {
  31584. var ib = this.getIndices();
  31585. if (!ib) {
  31586. return null;
  31587. }
  31588. var totalIndices = ib.length;
  31589. var needToRecreate = false;
  31590. if (force) {
  31591. needToRecreate = true;
  31592. }
  31593. else {
  31594. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31595. var submesh = _a[_i];
  31596. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31597. needToRecreate = true;
  31598. break;
  31599. }
  31600. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31601. needToRecreate = true;
  31602. break;
  31603. }
  31604. }
  31605. }
  31606. if (!needToRecreate) {
  31607. return this.subMeshes[0];
  31608. }
  31609. }
  31610. this.releaseSubMeshes();
  31611. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31612. };
  31613. Mesh.prototype.subdivide = function (count) {
  31614. if (count < 1) {
  31615. return;
  31616. }
  31617. var totalIndices = this.getTotalIndices();
  31618. var subdivisionSize = (totalIndices / count) | 0;
  31619. var offset = 0;
  31620. // Ensure that subdivisionSize is a multiple of 3
  31621. while (subdivisionSize % 3 !== 0) {
  31622. subdivisionSize++;
  31623. }
  31624. this.releaseSubMeshes();
  31625. for (var index = 0; index < count; index++) {
  31626. if (offset >= totalIndices) {
  31627. break;
  31628. }
  31629. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31630. offset += subdivisionSize;
  31631. }
  31632. this.synchronizeInstances();
  31633. };
  31634. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31635. if (updatable === void 0) { updatable = false; }
  31636. if (!this._geometry) {
  31637. var vertexData = new BABYLON.VertexData();
  31638. vertexData.set(data, kind);
  31639. var scene = this.getScene();
  31640. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31641. }
  31642. else {
  31643. this._geometry.setVerticesData(kind, data, updatable, stride);
  31644. }
  31645. return this;
  31646. };
  31647. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31648. if (updatable === void 0) { updatable = true; }
  31649. var vb = this.getVertexBuffer(kind);
  31650. if (!vb || vb.isUpdatable() === updatable) {
  31651. return;
  31652. }
  31653. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31654. };
  31655. /**
  31656. * Sets the mesh VertexBuffer.
  31657. * Returns the Mesh.
  31658. */
  31659. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31660. if (!this._geometry) {
  31661. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31662. }
  31663. this._geometry.setVerticesBuffer(buffer);
  31664. return this;
  31665. };
  31666. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31667. if (!this._geometry) {
  31668. return this;
  31669. }
  31670. if (!makeItUnique) {
  31671. this._geometry.updateVerticesData(kind, data, updateExtends);
  31672. }
  31673. else {
  31674. this.makeGeometryUnique();
  31675. this.updateVerticesData(kind, data, updateExtends, false);
  31676. }
  31677. return this;
  31678. };
  31679. /**
  31680. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31681. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31682. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31683. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31684. * Returns the Mesh.
  31685. */
  31686. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31687. if (computeNormals === void 0) { computeNormals = true; }
  31688. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31689. if (!positions) {
  31690. return this;
  31691. }
  31692. positionFunction(positions);
  31693. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31694. if (computeNormals) {
  31695. var indices = this.getIndices();
  31696. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31697. if (!normals) {
  31698. return this;
  31699. }
  31700. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31701. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31702. }
  31703. return this;
  31704. };
  31705. /**
  31706. * Creates a un-shared specific occurence of the geometry for the mesh.
  31707. * Returns the Mesh.
  31708. */
  31709. Mesh.prototype.makeGeometryUnique = function () {
  31710. if (!this._geometry) {
  31711. return this;
  31712. }
  31713. var oldGeometry = this._geometry;
  31714. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31715. oldGeometry.releaseForMesh(this, true);
  31716. geometry.applyToMesh(this);
  31717. return this;
  31718. };
  31719. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31720. if (totalVertices === void 0) { totalVertices = null; }
  31721. if (updatable === void 0) { updatable = false; }
  31722. if (!this._geometry) {
  31723. var vertexData = new BABYLON.VertexData();
  31724. vertexData.indices = indices;
  31725. var scene = this.getScene();
  31726. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31727. }
  31728. else {
  31729. this._geometry.setIndices(indices, totalVertices, updatable);
  31730. }
  31731. return this;
  31732. };
  31733. /**
  31734. * Update the current index buffer
  31735. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31736. * Returns the Mesh.
  31737. */
  31738. Mesh.prototype.updateIndices = function (indices, offset) {
  31739. if (!this._geometry) {
  31740. return this;
  31741. }
  31742. this._geometry.updateIndices(indices, offset);
  31743. return this;
  31744. };
  31745. /**
  31746. * Invert the geometry to move from a right handed system to a left handed one.
  31747. * Returns the Mesh.
  31748. */
  31749. Mesh.prototype.toLeftHanded = function () {
  31750. if (!this._geometry) {
  31751. return this;
  31752. }
  31753. this._geometry.toLeftHanded();
  31754. return this;
  31755. };
  31756. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31757. if (!this._geometry) {
  31758. return this;
  31759. }
  31760. var engine = this.getScene().getEngine();
  31761. // Wireframe
  31762. var indexToBind;
  31763. if (this._unIndexed) {
  31764. indexToBind = null;
  31765. }
  31766. else {
  31767. switch (fillMode) {
  31768. case BABYLON.Material.PointFillMode:
  31769. indexToBind = null;
  31770. break;
  31771. case BABYLON.Material.WireFrameFillMode:
  31772. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31773. break;
  31774. default:
  31775. case BABYLON.Material.TriangleFillMode:
  31776. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31777. break;
  31778. }
  31779. }
  31780. // VBOs
  31781. this._geometry._bind(effect, indexToBind);
  31782. return this;
  31783. };
  31784. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31785. if (alternate === void 0) { alternate = false; }
  31786. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31787. return this;
  31788. }
  31789. this.onBeforeDrawObservable.notifyObservers(this);
  31790. var scene = this.getScene();
  31791. var engine = scene.getEngine();
  31792. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31793. // or triangles as points
  31794. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31795. }
  31796. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31797. // Triangles as wireframe
  31798. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31799. }
  31800. else {
  31801. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31802. }
  31803. if (scene._isAlternateRenderingEnabled && !alternate) {
  31804. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31805. if (!effect || !scene.activeCamera) {
  31806. return this;
  31807. }
  31808. scene._switchToAlternateCameraConfiguration(true);
  31809. this._effectiveMaterial.bindView(effect);
  31810. this._effectiveMaterial.bindViewProjection(effect);
  31811. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31812. this._draw(subMesh, fillMode, instancesCount, true);
  31813. engine.setViewport(scene.activeCamera.viewport);
  31814. scene._switchToAlternateCameraConfiguration(false);
  31815. this._effectiveMaterial.bindView(effect);
  31816. this._effectiveMaterial.bindViewProjection(effect);
  31817. }
  31818. return this;
  31819. };
  31820. /**
  31821. * Registers for this mesh a javascript function called just before the rendering process.
  31822. * This function is passed the current mesh.
  31823. * Return the Mesh.
  31824. */
  31825. Mesh.prototype.registerBeforeRender = function (func) {
  31826. this.onBeforeRenderObservable.add(func);
  31827. return this;
  31828. };
  31829. /**
  31830. * Disposes a previously registered javascript function called before the rendering.
  31831. * This function is passed the current mesh.
  31832. * Returns the Mesh.
  31833. */
  31834. Mesh.prototype.unregisterBeforeRender = function (func) {
  31835. this.onBeforeRenderObservable.removeCallback(func);
  31836. return this;
  31837. };
  31838. /**
  31839. * Registers for this mesh a javascript function called just after the rendering is complete.
  31840. * This function is passed the current mesh.
  31841. * Returns the Mesh.
  31842. */
  31843. Mesh.prototype.registerAfterRender = function (func) {
  31844. this.onAfterRenderObservable.add(func);
  31845. return this;
  31846. };
  31847. /**
  31848. * Disposes a previously registered javascript function called after the rendering.
  31849. * This function is passed the current mesh.
  31850. * Return the Mesh.
  31851. */
  31852. Mesh.prototype.unregisterAfterRender = function (func) {
  31853. this.onAfterRenderObservable.removeCallback(func);
  31854. return this;
  31855. };
  31856. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31857. var scene = this.getScene();
  31858. this._batchCache.mustReturn = false;
  31859. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31860. this._batchCache.visibleInstances[subMeshId] = null;
  31861. if (this._visibleInstances) {
  31862. var currentRenderId = scene.getRenderId();
  31863. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31864. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31865. var selfRenderId = this._renderId;
  31866. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31867. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31868. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31869. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31870. }
  31871. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31872. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31873. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31874. this._batchCache.mustReturn = true;
  31875. return this._batchCache;
  31876. }
  31877. if (currentRenderId !== selfRenderId) {
  31878. this._batchCache.renderSelf[subMeshId] = false;
  31879. }
  31880. }
  31881. this._renderIdForInstances[subMeshId] = currentRenderId;
  31882. }
  31883. return this._batchCache;
  31884. };
  31885. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31886. var visibleInstances = batch.visibleInstances[subMesh._id];
  31887. if (!visibleInstances) {
  31888. return this;
  31889. }
  31890. var matricesCount = visibleInstances.length + 1;
  31891. var bufferSize = matricesCount * 16 * 4;
  31892. var currentInstancesBufferSize = this._instancesBufferSize;
  31893. var instancesBuffer = this._instancesBuffer;
  31894. while (this._instancesBufferSize < bufferSize) {
  31895. this._instancesBufferSize *= 2;
  31896. }
  31897. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31898. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31899. }
  31900. var offset = 0;
  31901. var instancesCount = 0;
  31902. var world = this.getWorldMatrix();
  31903. if (batch.renderSelf[subMesh._id]) {
  31904. world.copyToArray(this._instancesData, offset);
  31905. offset += 16;
  31906. instancesCount++;
  31907. }
  31908. if (visibleInstances) {
  31909. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31910. var instance = visibleInstances[instanceIndex];
  31911. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31912. offset += 16;
  31913. instancesCount++;
  31914. }
  31915. }
  31916. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31917. if (instancesBuffer) {
  31918. instancesBuffer.dispose();
  31919. }
  31920. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31921. this._instancesBuffer = instancesBuffer;
  31922. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31923. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31924. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31925. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31926. }
  31927. else {
  31928. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31929. }
  31930. this._bind(subMesh, effect, fillMode);
  31931. this._draw(subMesh, fillMode, instancesCount);
  31932. engine.unbindInstanceAttributes();
  31933. return this;
  31934. };
  31935. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31936. var scene = this.getScene();
  31937. var engine = scene.getEngine();
  31938. if (hardwareInstancedRendering) {
  31939. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31940. }
  31941. else {
  31942. if (batch.renderSelf[subMesh._id]) {
  31943. // Draw
  31944. if (onBeforeDraw) {
  31945. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31946. }
  31947. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31948. }
  31949. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31950. if (visibleInstancesForSubMesh) {
  31951. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31952. var instance = visibleInstancesForSubMesh[instanceIndex];
  31953. // World
  31954. var world = instance.getWorldMatrix();
  31955. if (onBeforeDraw) {
  31956. onBeforeDraw(true, world, effectiveMaterial);
  31957. }
  31958. // Draw
  31959. this._draw(subMesh, fillMode);
  31960. }
  31961. }
  31962. }
  31963. return this;
  31964. };
  31965. /**
  31966. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  31967. * @param subMesh defines the subMesh to render
  31968. * @param enableAlphaMode defines if alpha mode can be changed
  31969. * @returns the current mesh
  31970. */
  31971. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31972. this._checkOcclusionQuery();
  31973. if (this._isOccluded) {
  31974. return this;
  31975. }
  31976. var scene = this.getScene();
  31977. // Managing instances
  31978. var batch = this._getInstancesRenderList(subMesh._id);
  31979. if (batch.mustReturn) {
  31980. return this;
  31981. }
  31982. // Checking geometry state
  31983. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31984. return this;
  31985. }
  31986. this.onBeforeRenderObservable.notifyObservers(this);
  31987. var engine = scene.getEngine();
  31988. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31989. // Material
  31990. var material = subMesh.getMaterial();
  31991. if (!material) {
  31992. return this;
  31993. }
  31994. this._effectiveMaterial = material;
  31995. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31996. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31997. return this;
  31998. }
  31999. }
  32000. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32001. return this;
  32002. }
  32003. // Alpha mode
  32004. if (enableAlphaMode) {
  32005. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32006. }
  32007. // Outline - step 1
  32008. var savedDepthWrite = engine.getDepthWrite();
  32009. if (this.renderOutline) {
  32010. engine.setDepthWrite(false);
  32011. scene.getOutlineRenderer().render(subMesh, batch);
  32012. engine.setDepthWrite(savedDepthWrite);
  32013. }
  32014. var effect;
  32015. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32016. effect = subMesh.effect;
  32017. }
  32018. else {
  32019. effect = this._effectiveMaterial.getEffect();
  32020. }
  32021. if (!effect) {
  32022. return this;
  32023. }
  32024. var sideOrientation = this.overrideMaterialSideOrientation;
  32025. if (sideOrientation == null) {
  32026. sideOrientation = this._effectiveMaterial.sideOrientation;
  32027. if (this._getWorldMatrixDeterminant() < 0) {
  32028. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32029. }
  32030. }
  32031. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32032. if (this._effectiveMaterial.forceDepthWrite) {
  32033. engine.setDepthWrite(true);
  32034. }
  32035. // Bind
  32036. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32037. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32038. this._bind(subMesh, effect, fillMode);
  32039. }
  32040. var world = this.getWorldMatrix();
  32041. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32042. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32043. }
  32044. else {
  32045. this._effectiveMaterial.bind(world, this);
  32046. }
  32047. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32048. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32049. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32050. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32051. }
  32052. // Draw
  32053. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32054. // Unbind
  32055. this._effectiveMaterial.unbind();
  32056. // Outline - step 2
  32057. if (this.renderOutline && savedDepthWrite) {
  32058. engine.setDepthWrite(true);
  32059. engine.setColorWrite(false);
  32060. scene.getOutlineRenderer().render(subMesh, batch);
  32061. engine.setColorWrite(true);
  32062. }
  32063. // Overlay
  32064. if (this.renderOverlay) {
  32065. var currentMode = engine.getAlphaMode();
  32066. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32067. scene.getOutlineRenderer().render(subMesh, batch, true);
  32068. engine.setAlphaMode(currentMode);
  32069. }
  32070. this.onAfterRenderObservable.notifyObservers(this);
  32071. return this;
  32072. };
  32073. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32074. if (isInstance && effectiveMaterial) {
  32075. effectiveMaterial.bindOnlyWorldMatrix(world);
  32076. }
  32077. };
  32078. /**
  32079. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32080. */
  32081. Mesh.prototype.getEmittedParticleSystems = function () {
  32082. var results = new Array();
  32083. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32084. var particleSystem = this.getScene().particleSystems[index];
  32085. if (particleSystem.emitter === this) {
  32086. results.push(particleSystem);
  32087. }
  32088. }
  32089. return results;
  32090. };
  32091. /**
  32092. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32093. */
  32094. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32095. var results = new Array();
  32096. var descendants = this.getDescendants();
  32097. descendants.push(this);
  32098. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32099. var particleSystem = this.getScene().particleSystems[index];
  32100. var emitter = particleSystem.emitter;
  32101. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32102. results.push(particleSystem);
  32103. }
  32104. }
  32105. return results;
  32106. };
  32107. /**
  32108. * Normalize matrix weights so that all vertices have a total weight set to 1
  32109. */
  32110. Mesh.prototype.cleanMatrixWeights = function () {
  32111. var epsilon = 1e-3;
  32112. var noInfluenceBoneIndex = 0.0;
  32113. if (this.skeleton) {
  32114. noInfluenceBoneIndex = this.skeleton.bones.length;
  32115. }
  32116. else {
  32117. return;
  32118. }
  32119. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32120. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32121. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32122. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32123. var influencers = this.numBoneInfluencers;
  32124. var size = matricesWeights.length;
  32125. for (var i = 0; i < size; i += 4) {
  32126. var weight = 0.0;
  32127. var firstZeroWeight = -1;
  32128. for (var j = 0; j < 4; j++) {
  32129. var w = matricesWeights[i + j];
  32130. weight += w;
  32131. if (w < epsilon && firstZeroWeight < 0) {
  32132. firstZeroWeight = j;
  32133. }
  32134. }
  32135. if (matricesWeightsExtra) {
  32136. for (var j = 0; j < 4; j++) {
  32137. var w = matricesWeightsExtra[i + j];
  32138. weight += w;
  32139. if (w < epsilon && firstZeroWeight < 0) {
  32140. firstZeroWeight = j + 4;
  32141. }
  32142. }
  32143. }
  32144. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32145. firstZeroWeight = influencers - 1;
  32146. }
  32147. if (weight > epsilon) {
  32148. var mweight = 1.0 / weight;
  32149. for (var j = 0; j < 4; j++) {
  32150. matricesWeights[i + j] *= mweight;
  32151. }
  32152. if (matricesWeightsExtra) {
  32153. for (var j = 0; j < 4; j++) {
  32154. matricesWeightsExtra[i + j] *= mweight;
  32155. }
  32156. }
  32157. }
  32158. else {
  32159. if (firstZeroWeight >= 4) {
  32160. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32161. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32162. }
  32163. else {
  32164. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32165. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32166. }
  32167. }
  32168. }
  32169. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32170. if (matricesIndicesExtra) {
  32171. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32172. }
  32173. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32174. if (matricesWeightsExtra) {
  32175. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32176. }
  32177. };
  32178. Mesh.prototype._checkDelayState = function () {
  32179. var scene = this.getScene();
  32180. if (this._geometry) {
  32181. this._geometry.load(scene);
  32182. }
  32183. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32184. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32185. this._queueLoad(scene);
  32186. }
  32187. return this;
  32188. };
  32189. Mesh.prototype._queueLoad = function (scene) {
  32190. var _this = this;
  32191. scene._addPendingData(this);
  32192. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32193. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32194. if (data instanceof ArrayBuffer) {
  32195. _this._delayLoadingFunction(data, _this);
  32196. }
  32197. else {
  32198. _this._delayLoadingFunction(JSON.parse(data), _this);
  32199. }
  32200. _this.instances.forEach(function (instance) {
  32201. instance._syncSubMeshes();
  32202. });
  32203. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32204. scene._removePendingData(_this);
  32205. }, function () { }, scene.database, getBinaryData);
  32206. return this;
  32207. };
  32208. /**
  32209. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32210. */
  32211. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32212. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32213. return false;
  32214. }
  32215. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32216. return false;
  32217. }
  32218. this._checkDelayState();
  32219. return true;
  32220. };
  32221. /**
  32222. * Sets the mesh material by the material or multiMaterial `id` property.
  32223. * The material `id` is a string identifying the material or the multiMaterial.
  32224. * This method returns the Mesh.
  32225. */
  32226. Mesh.prototype.setMaterialByID = function (id) {
  32227. var materials = this.getScene().materials;
  32228. var index;
  32229. for (index = materials.length - 1; index > -1; index--) {
  32230. if (materials[index].id === id) {
  32231. this.material = materials[index];
  32232. return this;
  32233. }
  32234. }
  32235. // Multi
  32236. var multiMaterials = this.getScene().multiMaterials;
  32237. for (index = multiMaterials.length - 1; index > -1; index--) {
  32238. if (multiMaterials[index].id === id) {
  32239. this.material = multiMaterials[index];
  32240. return this;
  32241. }
  32242. }
  32243. return this;
  32244. };
  32245. /**
  32246. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32247. */
  32248. Mesh.prototype.getAnimatables = function () {
  32249. var results = new Array();
  32250. if (this.material) {
  32251. results.push(this.material);
  32252. }
  32253. if (this.skeleton) {
  32254. results.push(this.skeleton);
  32255. }
  32256. return results;
  32257. };
  32258. /**
  32259. * Modifies the mesh geometry according to the passed transformation matrix.
  32260. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32261. * The mesh normals are modified accordingly the same transformation.
  32262. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32263. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32264. * Returns the Mesh.
  32265. */
  32266. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32267. // Position
  32268. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32269. return this;
  32270. }
  32271. var submeshes = this.subMeshes.splice(0);
  32272. this._resetPointsArrayCache();
  32273. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32274. var temp = new Array();
  32275. var index;
  32276. for (index = 0; index < data.length; index += 3) {
  32277. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32278. }
  32279. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32280. // Normals
  32281. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32282. return this;
  32283. }
  32284. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32285. temp = [];
  32286. for (index = 0; index < data.length; index += 3) {
  32287. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32288. }
  32289. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32290. // flip faces?
  32291. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32292. this.flipFaces();
  32293. }
  32294. // Restore submeshes
  32295. this.releaseSubMeshes();
  32296. this.subMeshes = submeshes;
  32297. return this;
  32298. };
  32299. /**
  32300. * Modifies the mesh geometry according to its own current World Matrix.
  32301. * The mesh World Matrix is then reset.
  32302. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32303. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32304. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32305. * Returns the Mesh.
  32306. */
  32307. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32308. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32309. this.scaling.copyFromFloats(1, 1, 1);
  32310. this.position.copyFromFloats(0, 0, 0);
  32311. this.rotation.copyFromFloats(0, 0, 0);
  32312. //only if quaternion is already set
  32313. if (this.rotationQuaternion) {
  32314. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32315. }
  32316. this._worldMatrix = BABYLON.Matrix.Identity();
  32317. return this;
  32318. };
  32319. Object.defineProperty(Mesh.prototype, "_positions", {
  32320. // Cache
  32321. get: function () {
  32322. if (this._geometry) {
  32323. return this._geometry._positions;
  32324. }
  32325. return null;
  32326. },
  32327. enumerable: true,
  32328. configurable: true
  32329. });
  32330. Mesh.prototype._resetPointsArrayCache = function () {
  32331. if (this._geometry) {
  32332. this._geometry._resetPointsArrayCache();
  32333. }
  32334. return this;
  32335. };
  32336. Mesh.prototype._generatePointsArray = function () {
  32337. if (this._geometry) {
  32338. return this._geometry._generatePointsArray();
  32339. }
  32340. return false;
  32341. };
  32342. /**
  32343. * Returns a new Mesh object generated from the current mesh properties.
  32344. * This method must not get confused with createInstance().
  32345. * The parameter `name` is a string, the name given to the new mesh.
  32346. * The optional parameter `newParent` can be any Node object (default `null`).
  32347. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32348. * 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.
  32349. */
  32350. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32351. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32352. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32353. };
  32354. /**
  32355. * Releases resources associated with this mesh.
  32356. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32357. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32358. */
  32359. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32360. var _this = this;
  32361. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32362. this.morphTargetManager = null;
  32363. if (this._geometry) {
  32364. this._geometry.releaseForMesh(this, true);
  32365. }
  32366. // Sources
  32367. var meshes = this.getScene().meshes;
  32368. meshes.forEach(function (abstractMesh) {
  32369. var mesh = abstractMesh;
  32370. if (mesh._source && mesh._source === _this) {
  32371. mesh._source = null;
  32372. }
  32373. });
  32374. this._source = null;
  32375. // Instances
  32376. if (this._instancesBuffer) {
  32377. this._instancesBuffer.dispose();
  32378. this._instancesBuffer = null;
  32379. }
  32380. while (this.instances.length) {
  32381. this.instances[0].dispose();
  32382. }
  32383. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32384. };
  32385. /**
  32386. * Modifies the mesh geometry according to a displacement map.
  32387. * 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.
  32388. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32389. * This method returns nothing.
  32390. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32391. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32392. * 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.
  32393. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32394. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32395. *
  32396. * Returns the Mesh.
  32397. */
  32398. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32399. var _this = this;
  32400. var scene = this.getScene();
  32401. var onload = function (img) {
  32402. // Getting height map data
  32403. var canvas = document.createElement("canvas");
  32404. var context = canvas.getContext("2d");
  32405. var heightMapWidth = img.width;
  32406. var heightMapHeight = img.height;
  32407. canvas.width = heightMapWidth;
  32408. canvas.height = heightMapHeight;
  32409. context.drawImage(img, 0, 0);
  32410. // Create VertexData from map data
  32411. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32412. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32413. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32414. //execute success callback, if set
  32415. if (onSuccess) {
  32416. onSuccess(_this);
  32417. }
  32418. };
  32419. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32420. return this;
  32421. };
  32422. /**
  32423. * Modifies the mesh geometry according to a displacementMap buffer.
  32424. * 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.
  32425. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32426. * This method returns nothing.
  32427. * 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.
  32428. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32429. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32430. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32431. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32432. *
  32433. * Returns the Mesh.
  32434. */
  32435. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32436. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32437. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32438. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32439. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32440. return this;
  32441. }
  32442. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32443. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32444. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32445. var position = BABYLON.Vector3.Zero();
  32446. var normal = BABYLON.Vector3.Zero();
  32447. var uv = BABYLON.Vector2.Zero();
  32448. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32449. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32450. for (var index = 0; index < positions.length; index += 3) {
  32451. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32452. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32453. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32454. // Compute height
  32455. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32456. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32457. var pos = (u + v * heightMapWidth) * 4;
  32458. var r = buffer[pos] / 255.0;
  32459. var g = buffer[pos + 1] / 255.0;
  32460. var b = buffer[pos + 2] / 255.0;
  32461. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32462. normal.normalize();
  32463. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32464. position = position.add(normal);
  32465. position.toArray(positions, index);
  32466. }
  32467. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32468. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32469. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32470. return this;
  32471. };
  32472. /**
  32473. * Modify the mesh to get a flat shading rendering.
  32474. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32475. * This method returns the Mesh.
  32476. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32477. */
  32478. Mesh.prototype.convertToFlatShadedMesh = function () {
  32479. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32480. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32481. var kinds = this.getVerticesDataKinds();
  32482. var vbs = {};
  32483. var data = {};
  32484. var newdata = {};
  32485. var updatableNormals = false;
  32486. var kindIndex;
  32487. var kind;
  32488. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32489. kind = kinds[kindIndex];
  32490. var vertexBuffer = this.getVertexBuffer(kind);
  32491. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32492. updatableNormals = vertexBuffer.isUpdatable();
  32493. kinds.splice(kindIndex, 1);
  32494. kindIndex--;
  32495. continue;
  32496. }
  32497. vbs[kind] = vertexBuffer;
  32498. data[kind] = vbs[kind].getData();
  32499. newdata[kind] = [];
  32500. }
  32501. // Save previous submeshes
  32502. var previousSubmeshes = this.subMeshes.slice(0);
  32503. var indices = this.getIndices();
  32504. var totalIndices = this.getTotalIndices();
  32505. // Generating unique vertices per face
  32506. var index;
  32507. for (index = 0; index < totalIndices; index++) {
  32508. var vertexIndex = indices[index];
  32509. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32510. kind = kinds[kindIndex];
  32511. var stride = vbs[kind].getStrideSize();
  32512. for (var offset = 0; offset < stride; offset++) {
  32513. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32514. }
  32515. }
  32516. }
  32517. // Updating faces & normal
  32518. var normals = [];
  32519. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32520. for (index = 0; index < totalIndices; index += 3) {
  32521. indices[index] = index;
  32522. indices[index + 1] = index + 1;
  32523. indices[index + 2] = index + 2;
  32524. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32525. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32526. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32527. var p1p2 = p1.subtract(p2);
  32528. var p3p2 = p3.subtract(p2);
  32529. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32530. // Store same normals for every vertex
  32531. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32532. normals.push(normal.x);
  32533. normals.push(normal.y);
  32534. normals.push(normal.z);
  32535. }
  32536. }
  32537. this.setIndices(indices);
  32538. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32539. // Updating vertex buffers
  32540. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32541. kind = kinds[kindIndex];
  32542. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32543. }
  32544. // Updating submeshes
  32545. this.releaseSubMeshes();
  32546. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32547. var previousOne = previousSubmeshes[submeshIndex];
  32548. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32549. }
  32550. this.synchronizeInstances();
  32551. return this;
  32552. };
  32553. /**
  32554. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32555. * In other words, more vertices, no more indices and a single bigger VBO.
  32556. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32557. * Returns the Mesh.
  32558. */
  32559. Mesh.prototype.convertToUnIndexedMesh = function () {
  32560. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32561. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32562. var kinds = this.getVerticesDataKinds();
  32563. var vbs = {};
  32564. var data = {};
  32565. var newdata = {};
  32566. var kindIndex;
  32567. var kind;
  32568. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32569. kind = kinds[kindIndex];
  32570. var vertexBuffer = this.getVertexBuffer(kind);
  32571. vbs[kind] = vertexBuffer;
  32572. data[kind] = vbs[kind].getData();
  32573. newdata[kind] = [];
  32574. }
  32575. // Save previous submeshes
  32576. var previousSubmeshes = this.subMeshes.slice(0);
  32577. var indices = this.getIndices();
  32578. var totalIndices = this.getTotalIndices();
  32579. // Generating unique vertices per face
  32580. var index;
  32581. for (index = 0; index < totalIndices; index++) {
  32582. var vertexIndex = indices[index];
  32583. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32584. kind = kinds[kindIndex];
  32585. var stride = vbs[kind].getStrideSize();
  32586. for (var offset = 0; offset < stride; offset++) {
  32587. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32588. }
  32589. }
  32590. }
  32591. // Updating indices
  32592. for (index = 0; index < totalIndices; index += 3) {
  32593. indices[index] = index;
  32594. indices[index + 1] = index + 1;
  32595. indices[index + 2] = index + 2;
  32596. }
  32597. this.setIndices(indices);
  32598. // Updating vertex buffers
  32599. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32600. kind = kinds[kindIndex];
  32601. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32602. }
  32603. // Updating submeshes
  32604. this.releaseSubMeshes();
  32605. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32606. var previousOne = previousSubmeshes[submeshIndex];
  32607. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32608. }
  32609. this._unIndexed = true;
  32610. this.synchronizeInstances();
  32611. return this;
  32612. };
  32613. /**
  32614. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32615. * This method returns the Mesh.
  32616. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32617. */
  32618. Mesh.prototype.flipFaces = function (flipNormals) {
  32619. if (flipNormals === void 0) { flipNormals = false; }
  32620. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32621. var i;
  32622. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32623. for (i = 0; i < vertex_data.normals.length; i++) {
  32624. vertex_data.normals[i] *= -1;
  32625. }
  32626. }
  32627. if (vertex_data.indices) {
  32628. var temp;
  32629. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32630. // reassign indices
  32631. temp = vertex_data.indices[i + 1];
  32632. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32633. vertex_data.indices[i + 2] = temp;
  32634. }
  32635. }
  32636. vertex_data.applyToMesh(this);
  32637. return this;
  32638. };
  32639. // Instances
  32640. /**
  32641. * Creates a new InstancedMesh object from the mesh model.
  32642. * An instance shares the same properties and the same material than its model.
  32643. * Only these properties of each instance can then be set individually :
  32644. * - position
  32645. * - rotation
  32646. * - rotationQuaternion
  32647. * - setPivotMatrix
  32648. * - scaling
  32649. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32650. * Warning : this method is not supported for Line mesh and LineSystem
  32651. */
  32652. Mesh.prototype.createInstance = function (name) {
  32653. return new BABYLON.InstancedMesh(name, this);
  32654. };
  32655. /**
  32656. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32657. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32658. * This method returns the Mesh.
  32659. */
  32660. Mesh.prototype.synchronizeInstances = function () {
  32661. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32662. var instance = this.instances[instanceIndex];
  32663. instance._syncSubMeshes();
  32664. }
  32665. return this;
  32666. };
  32667. /**
  32668. * Simplify the mesh according to the given array of settings.
  32669. * Function will return immediately and will simplify async. It returns the Mesh.
  32670. * @param settings a collection of simplification settings.
  32671. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32672. * @param type the type of simplification to run.
  32673. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32674. */
  32675. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32676. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32677. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32678. this.getScene().simplificationQueue.addTask({
  32679. settings: settings,
  32680. parallelProcessing: parallelProcessing,
  32681. mesh: this,
  32682. simplificationType: simplificationType,
  32683. successCallback: successCallback
  32684. });
  32685. return this;
  32686. };
  32687. /**
  32688. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32689. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32690. * This should be used together with the simplification to avoid disappearing triangles.
  32691. * Returns the Mesh.
  32692. * @param successCallback an optional success callback to be called after the optimization finished.
  32693. */
  32694. Mesh.prototype.optimizeIndices = function (successCallback) {
  32695. var _this = this;
  32696. var indices = this.getIndices();
  32697. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32698. if (!positions || !indices) {
  32699. return this;
  32700. }
  32701. var vectorPositions = new Array();
  32702. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32703. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32704. }
  32705. var dupes = new Array();
  32706. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32707. var realPos = vectorPositions.length - 1 - iteration;
  32708. var testedPosition = vectorPositions[realPos];
  32709. for (var j = 0; j < realPos; ++j) {
  32710. var againstPosition = vectorPositions[j];
  32711. if (testedPosition.equals(againstPosition)) {
  32712. dupes[realPos] = j;
  32713. break;
  32714. }
  32715. }
  32716. }, function () {
  32717. for (var i = 0; i < indices.length; ++i) {
  32718. indices[i] = dupes[indices[i]] || indices[i];
  32719. }
  32720. //indices are now reordered
  32721. var originalSubMeshes = _this.subMeshes.slice(0);
  32722. _this.setIndices(indices);
  32723. _this.subMeshes = originalSubMeshes;
  32724. if (successCallback) {
  32725. successCallback(_this);
  32726. }
  32727. });
  32728. return this;
  32729. };
  32730. Mesh.prototype.serialize = function (serializationObject) {
  32731. serializationObject.name = this.name;
  32732. serializationObject.id = this.id;
  32733. serializationObject.type = this.getClassName();
  32734. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32735. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32736. }
  32737. serializationObject.position = this.position.asArray();
  32738. if (this.rotationQuaternion) {
  32739. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32740. }
  32741. else if (this.rotation) {
  32742. serializationObject.rotation = this.rotation.asArray();
  32743. }
  32744. serializationObject.scaling = this.scaling.asArray();
  32745. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32746. serializationObject.isEnabled = this.isEnabled(false);
  32747. serializationObject.isVisible = this.isVisible;
  32748. serializationObject.infiniteDistance = this.infiniteDistance;
  32749. serializationObject.pickable = this.isPickable;
  32750. serializationObject.receiveShadows = this.receiveShadows;
  32751. serializationObject.billboardMode = this.billboardMode;
  32752. serializationObject.visibility = this.visibility;
  32753. serializationObject.checkCollisions = this.checkCollisions;
  32754. serializationObject.isBlocker = this.isBlocker;
  32755. // Parent
  32756. if (this.parent) {
  32757. serializationObject.parentId = this.parent.id;
  32758. }
  32759. // Geometry
  32760. serializationObject.isUnIndexed = this.isUnIndexed;
  32761. var geometry = this._geometry;
  32762. if (geometry) {
  32763. var geometryId = geometry.id;
  32764. serializationObject.geometryId = geometryId;
  32765. // SubMeshes
  32766. serializationObject.subMeshes = [];
  32767. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32768. var subMesh = this.subMeshes[subIndex];
  32769. serializationObject.subMeshes.push({
  32770. materialIndex: subMesh.materialIndex,
  32771. verticesStart: subMesh.verticesStart,
  32772. verticesCount: subMesh.verticesCount,
  32773. indexStart: subMesh.indexStart,
  32774. indexCount: subMesh.indexCount
  32775. });
  32776. }
  32777. }
  32778. // Material
  32779. if (this.material) {
  32780. serializationObject.materialId = this.material.id;
  32781. }
  32782. else {
  32783. this.material = null;
  32784. }
  32785. // Morph targets
  32786. if (this.morphTargetManager) {
  32787. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32788. }
  32789. // Skeleton
  32790. if (this.skeleton) {
  32791. serializationObject.skeletonId = this.skeleton.id;
  32792. }
  32793. // Physics
  32794. //TODO implement correct serialization for physics impostors.
  32795. var impostor = this.getPhysicsImpostor();
  32796. if (impostor) {
  32797. serializationObject.physicsMass = impostor.getParam("mass");
  32798. serializationObject.physicsFriction = impostor.getParam("friction");
  32799. serializationObject.physicsRestitution = impostor.getParam("mass");
  32800. serializationObject.physicsImpostor = impostor.type;
  32801. }
  32802. // Metadata
  32803. if (this.metadata) {
  32804. serializationObject.metadata = this.metadata;
  32805. }
  32806. // Instances
  32807. serializationObject.instances = [];
  32808. for (var index = 0; index < this.instances.length; index++) {
  32809. var instance = this.instances[index];
  32810. var serializationInstance = {
  32811. name: instance.name,
  32812. id: instance.id,
  32813. position: instance.position.asArray(),
  32814. scaling: instance.scaling.asArray()
  32815. };
  32816. if (instance.rotationQuaternion) {
  32817. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32818. }
  32819. else if (instance.rotation) {
  32820. serializationInstance.rotation = instance.rotation.asArray();
  32821. }
  32822. serializationObject.instances.push(serializationInstance);
  32823. // Animations
  32824. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32825. serializationInstance.ranges = instance.serializeAnimationRanges();
  32826. }
  32827. //
  32828. // Animations
  32829. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32830. serializationObject.ranges = this.serializeAnimationRanges();
  32831. // Layer mask
  32832. serializationObject.layerMask = this.layerMask;
  32833. // Alpha
  32834. serializationObject.alphaIndex = this.alphaIndex;
  32835. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32836. // Overlay
  32837. serializationObject.overlayAlpha = this.overlayAlpha;
  32838. serializationObject.overlayColor = this.overlayColor.asArray();
  32839. serializationObject.renderOverlay = this.renderOverlay;
  32840. // Fog
  32841. serializationObject.applyFog = this.applyFog;
  32842. // Action Manager
  32843. if (this.actionManager) {
  32844. serializationObject.actions = this.actionManager.serialize(this.name);
  32845. }
  32846. };
  32847. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32848. if (!this.geometry) {
  32849. return;
  32850. }
  32851. this._markSubMeshesAsAttributesDirty();
  32852. var morphTargetManager = this._morphTargetManager;
  32853. if (morphTargetManager && morphTargetManager.vertexCount) {
  32854. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32855. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32856. this.morphTargetManager = null;
  32857. return;
  32858. }
  32859. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32860. var morphTarget = morphTargetManager.getActiveTarget(index);
  32861. var positions = morphTarget.getPositions();
  32862. if (!positions) {
  32863. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32864. return;
  32865. }
  32866. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32867. var normals = morphTarget.getNormals();
  32868. if (normals) {
  32869. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32870. }
  32871. var tangents = morphTarget.getTangents();
  32872. if (tangents) {
  32873. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32874. }
  32875. }
  32876. }
  32877. else {
  32878. var index = 0;
  32879. // Positions
  32880. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32881. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32882. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32883. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32884. }
  32885. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32886. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32887. }
  32888. index++;
  32889. }
  32890. }
  32891. };
  32892. // Statics
  32893. /**
  32894. * Returns a new Mesh object parsed from the source provided.
  32895. * The parameter `parsedMesh` is the source.
  32896. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32897. */
  32898. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32899. var mesh;
  32900. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32901. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32902. }
  32903. else {
  32904. mesh = new Mesh(parsedMesh.name, scene);
  32905. }
  32906. mesh.id = parsedMesh.id;
  32907. if (BABYLON.Tags) {
  32908. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32909. }
  32910. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32911. if (parsedMesh.metadata !== undefined) {
  32912. mesh.metadata = parsedMesh.metadata;
  32913. }
  32914. if (parsedMesh.rotationQuaternion) {
  32915. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32916. }
  32917. else if (parsedMesh.rotation) {
  32918. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32919. }
  32920. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32921. if (parsedMesh.localMatrix) {
  32922. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32923. }
  32924. else if (parsedMesh.pivotMatrix) {
  32925. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32926. }
  32927. mesh.setEnabled(parsedMesh.isEnabled);
  32928. mesh.isVisible = parsedMesh.isVisible;
  32929. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32930. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32931. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32932. if (parsedMesh.applyFog !== undefined) {
  32933. mesh.applyFog = parsedMesh.applyFog;
  32934. }
  32935. if (parsedMesh.pickable !== undefined) {
  32936. mesh.isPickable = parsedMesh.pickable;
  32937. }
  32938. if (parsedMesh.alphaIndex !== undefined) {
  32939. mesh.alphaIndex = parsedMesh.alphaIndex;
  32940. }
  32941. mesh.receiveShadows = parsedMesh.receiveShadows;
  32942. mesh.billboardMode = parsedMesh.billboardMode;
  32943. if (parsedMesh.visibility !== undefined) {
  32944. mesh.visibility = parsedMesh.visibility;
  32945. }
  32946. mesh.checkCollisions = parsedMesh.checkCollisions;
  32947. if (parsedMesh.isBlocker !== undefined) {
  32948. mesh.isBlocker = parsedMesh.isBlocker;
  32949. }
  32950. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32951. // freezeWorldMatrix
  32952. if (parsedMesh.freezeWorldMatrix) {
  32953. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32954. }
  32955. // Parent
  32956. if (parsedMesh.parentId) {
  32957. mesh._waitingParentId = parsedMesh.parentId;
  32958. }
  32959. // Actions
  32960. if (parsedMesh.actions !== undefined) {
  32961. mesh._waitingActions = parsedMesh.actions;
  32962. }
  32963. // Overlay
  32964. if (parsedMesh.overlayAlpha !== undefined) {
  32965. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32966. }
  32967. if (parsedMesh.overlayColor !== undefined) {
  32968. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32969. }
  32970. if (parsedMesh.renderOverlay !== undefined) {
  32971. mesh.renderOverlay = parsedMesh.renderOverlay;
  32972. }
  32973. // Geometry
  32974. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32975. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32976. if (parsedMesh.delayLoadingFile) {
  32977. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32978. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32979. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32980. if (parsedMesh._binaryInfo) {
  32981. mesh._binaryInfo = parsedMesh._binaryInfo;
  32982. }
  32983. mesh._delayInfo = [];
  32984. if (parsedMesh.hasUVs) {
  32985. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32986. }
  32987. if (parsedMesh.hasUVs2) {
  32988. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32989. }
  32990. if (parsedMesh.hasUVs3) {
  32991. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32992. }
  32993. if (parsedMesh.hasUVs4) {
  32994. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32995. }
  32996. if (parsedMesh.hasUVs5) {
  32997. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32998. }
  32999. if (parsedMesh.hasUVs6) {
  33000. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33001. }
  33002. if (parsedMesh.hasColors) {
  33003. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33004. }
  33005. if (parsedMesh.hasMatricesIndices) {
  33006. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33007. }
  33008. if (parsedMesh.hasMatricesWeights) {
  33009. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33010. }
  33011. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33012. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33013. mesh._checkDelayState();
  33014. }
  33015. }
  33016. else {
  33017. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33018. }
  33019. // Material
  33020. if (parsedMesh.materialId) {
  33021. mesh.setMaterialByID(parsedMesh.materialId);
  33022. }
  33023. else {
  33024. mesh.material = null;
  33025. }
  33026. // Morph targets
  33027. if (parsedMesh.morphTargetManagerId > -1) {
  33028. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33029. }
  33030. // Skeleton
  33031. if (parsedMesh.skeletonId > -1) {
  33032. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33033. if (parsedMesh.numBoneInfluencers) {
  33034. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33035. }
  33036. }
  33037. // Animations
  33038. if (parsedMesh.animations) {
  33039. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33040. var parsedAnimation = parsedMesh.animations[animationIndex];
  33041. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33042. }
  33043. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33044. }
  33045. if (parsedMesh.autoAnimate) {
  33046. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33047. }
  33048. // Layer Mask
  33049. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33050. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33051. }
  33052. else {
  33053. mesh.layerMask = 0x0FFFFFFF;
  33054. }
  33055. // Physics
  33056. if (parsedMesh.physicsImpostor) {
  33057. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33058. mass: parsedMesh.physicsMass,
  33059. friction: parsedMesh.physicsFriction,
  33060. restitution: parsedMesh.physicsRestitution
  33061. }, scene);
  33062. }
  33063. // Instances
  33064. if (parsedMesh.instances) {
  33065. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33066. var parsedInstance = parsedMesh.instances[index];
  33067. var instance = mesh.createInstance(parsedInstance.name);
  33068. if (parsedInstance.id) {
  33069. instance.id = parsedInstance.id;
  33070. }
  33071. if (BABYLON.Tags) {
  33072. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33073. }
  33074. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33075. if (parsedInstance.parentId) {
  33076. instance._waitingParentId = parsedInstance.parentId;
  33077. }
  33078. if (parsedInstance.rotationQuaternion) {
  33079. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33080. }
  33081. else if (parsedInstance.rotation) {
  33082. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33083. }
  33084. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33085. instance.checkCollisions = mesh.checkCollisions;
  33086. if (parsedMesh.animations) {
  33087. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33088. parsedAnimation = parsedMesh.animations[animationIndex];
  33089. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33090. }
  33091. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33092. if (parsedMesh.autoAnimate) {
  33093. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33094. }
  33095. }
  33096. }
  33097. }
  33098. return mesh;
  33099. };
  33100. /**
  33101. * Creates a ribbon mesh.
  33102. * Please consider using the same method from the MeshBuilder class instead.
  33103. * 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.
  33104. *
  33105. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33106. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33107. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33108. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33109. * 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.
  33110. * 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.
  33111. * 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
  33112. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33113. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33115. */
  33116. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33117. if (closeArray === void 0) { closeArray = false; }
  33118. if (updatable === void 0) { updatable = false; }
  33119. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33120. pathArray: pathArray,
  33121. closeArray: closeArray,
  33122. closePath: closePath,
  33123. offset: offset,
  33124. updatable: updatable,
  33125. sideOrientation: sideOrientation,
  33126. instance: instance
  33127. }, scene);
  33128. };
  33129. /**
  33130. * Creates a plane polygonal mesh. By default, this is a disc.
  33131. * Please consider using the same method from the MeshBuilder class instead.
  33132. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33133. * 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.
  33134. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33135. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33136. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33137. */
  33138. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33139. if (scene === void 0) { scene = null; }
  33140. var options = {
  33141. radius: radius,
  33142. tessellation: tessellation,
  33143. sideOrientation: sideOrientation,
  33144. updatable: updatable
  33145. };
  33146. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33147. };
  33148. /**
  33149. * Creates a box mesh.
  33150. * Please consider using the same method from the MeshBuilder class instead.
  33151. * The parameter `size` sets the size (float) of each box side (default 1).
  33152. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33153. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33154. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33155. */
  33156. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33157. if (scene === void 0) { scene = null; }
  33158. var options = {
  33159. size: size,
  33160. sideOrientation: sideOrientation,
  33161. updatable: updatable
  33162. };
  33163. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33164. };
  33165. /**
  33166. * Creates a sphere mesh.
  33167. * Please consider using the same method from the MeshBuilder class instead.
  33168. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33169. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33171. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33173. */
  33174. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33175. var options = {
  33176. segments: segments,
  33177. diameterX: diameter,
  33178. diameterY: diameter,
  33179. diameterZ: diameter,
  33180. sideOrientation: sideOrientation,
  33181. updatable: updatable
  33182. };
  33183. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33184. };
  33185. /**
  33186. * Creates a cylinder or a cone mesh.
  33187. * Please consider using the same method from the MeshBuilder class instead.
  33188. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33189. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33190. * 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.
  33191. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33192. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33193. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33194. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33196. */
  33197. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33198. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33199. if (scene !== undefined) {
  33200. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33201. updatable = scene;
  33202. }
  33203. scene = subdivisions;
  33204. subdivisions = 1;
  33205. }
  33206. var options = {
  33207. height: height,
  33208. diameterTop: diameterTop,
  33209. diameterBottom: diameterBottom,
  33210. tessellation: tessellation,
  33211. subdivisions: subdivisions,
  33212. sideOrientation: sideOrientation,
  33213. updatable: updatable
  33214. };
  33215. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33216. };
  33217. // Torus (Code from SharpDX.org)
  33218. /**
  33219. * Creates a torus mesh.
  33220. * Please consider using the same method from the MeshBuilder class instead.
  33221. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33222. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33223. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33224. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33225. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33227. */
  33228. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33229. var options = {
  33230. diameter: diameter,
  33231. thickness: thickness,
  33232. tessellation: tessellation,
  33233. sideOrientation: sideOrientation,
  33234. updatable: updatable
  33235. };
  33236. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33237. };
  33238. /**
  33239. * Creates a torus knot mesh.
  33240. * Please consider using the same method from the MeshBuilder class instead.
  33241. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33242. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33243. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33244. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33245. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33246. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33247. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33248. */
  33249. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33250. var options = {
  33251. radius: radius,
  33252. tube: tube,
  33253. radialSegments: radialSegments,
  33254. tubularSegments: tubularSegments,
  33255. p: p,
  33256. q: q,
  33257. sideOrientation: sideOrientation,
  33258. updatable: updatable
  33259. };
  33260. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33261. };
  33262. /**
  33263. * Creates a line mesh.
  33264. * Please consider using the same method from the MeshBuilder class instead.
  33265. * 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.
  33266. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33267. * The parameter `points` is an array successive Vector3.
  33268. * 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
  33269. * When updating an instance, remember that only point positions can change, not the number of points.
  33270. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33271. */
  33272. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33273. if (scene === void 0) { scene = null; }
  33274. if (updatable === void 0) { updatable = false; }
  33275. if (instance === void 0) { instance = null; }
  33276. var options = {
  33277. points: points,
  33278. updatable: updatable,
  33279. instance: instance
  33280. };
  33281. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33282. };
  33283. /**
  33284. * Creates a dashed line mesh.
  33285. * Please consider using the same method from the MeshBuilder class instead.
  33286. * 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.
  33287. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33288. * The parameter `points` is an array successive Vector3.
  33289. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33290. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33291. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33292. * 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
  33293. * When updating an instance, remember that only point positions can change, not the number of points.
  33294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33295. */
  33296. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33297. if (scene === void 0) { scene = null; }
  33298. var options = {
  33299. points: points,
  33300. dashSize: dashSize,
  33301. gapSize: gapSize,
  33302. dashNb: dashNb,
  33303. updatable: updatable,
  33304. instance: instance
  33305. };
  33306. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33307. };
  33308. /**
  33309. * Creates a polygon mesh.
  33310. * Please consider using the same method from the MeshBuilder class instead.
  33311. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33312. * 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.
  33313. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33315. * Remember you can only change the shape positions, not their number when updating a polygon.
  33316. */
  33317. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33318. var options = {
  33319. shape: shape,
  33320. holes: holes,
  33321. updatable: updatable,
  33322. sideOrientation: sideOrientation
  33323. };
  33324. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33325. };
  33326. /**
  33327. * Creates an extruded polygon mesh, with depth in the Y direction.
  33328. * Please consider using the same method from the MeshBuilder class instead.
  33329. */
  33330. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33331. var options = {
  33332. shape: shape,
  33333. holes: holes,
  33334. depth: depth,
  33335. updatable: updatable,
  33336. sideOrientation: sideOrientation
  33337. };
  33338. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33339. };
  33340. /**
  33341. * Creates an extruded shape mesh.
  33342. * 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.
  33343. * Please consider using the same method from the MeshBuilder class instead.
  33344. *
  33345. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33346. * 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
  33347. * extruded along the Z axis.
  33348. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33349. * 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.
  33350. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33351. * 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
  33352. * 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
  33353. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33354. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33355. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  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.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33359. if (scene === void 0) { scene = null; }
  33360. var options = {
  33361. shape: shape,
  33362. path: path,
  33363. scale: scale,
  33364. rotation: rotation,
  33365. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33366. sideOrientation: sideOrientation,
  33367. instance: instance,
  33368. updatable: updatable
  33369. };
  33370. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33371. };
  33372. /**
  33373. * Creates an custom extruded shape mesh.
  33374. * 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.
  33375. * Please consider using the same method from the MeshBuilder class instead.
  33376. *
  33377. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33378. * 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
  33379. * extruded along the Z axis.
  33380. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33381. * 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
  33382. * and the distance of this point from the begining of the path :
  33383. * ```javascript
  33384. * var rotationFunction = function(i, distance) {
  33385. * // do things
  33386. * return rotationValue; }
  33387. * ```
  33388. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33389. * 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
  33390. * and the distance of this point from the begining of the path :
  33391. * ```javascript
  33392. * var scaleFunction = function(i, distance) {
  33393. * // do things
  33394. * return scaleValue;}
  33395. * ```
  33396. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33397. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33398. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33399. * 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
  33400. * 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
  33401. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33402. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33403. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33405. */
  33406. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33407. var options = {
  33408. shape: shape,
  33409. path: path,
  33410. scaleFunction: scaleFunction,
  33411. rotationFunction: rotationFunction,
  33412. ribbonCloseArray: ribbonCloseArray,
  33413. ribbonClosePath: ribbonClosePath,
  33414. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33415. sideOrientation: sideOrientation,
  33416. instance: instance,
  33417. updatable: updatable
  33418. };
  33419. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33420. };
  33421. /**
  33422. * Creates lathe mesh.
  33423. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33424. * Please consider using the same method from the MeshBuilder class instead.
  33425. * 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
  33426. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33427. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33428. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33429. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33430. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33432. */
  33433. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33434. var options = {
  33435. shape: shape,
  33436. radius: radius,
  33437. tessellation: tessellation,
  33438. sideOrientation: sideOrientation,
  33439. updatable: updatable
  33440. };
  33441. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33442. };
  33443. /**
  33444. * Creates a plane mesh.
  33445. * Please consider using the same method from the MeshBuilder class instead.
  33446. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33447. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33448. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33450. */
  33451. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33452. var options = {
  33453. size: size,
  33454. width: size,
  33455. height: size,
  33456. sideOrientation: sideOrientation,
  33457. updatable: updatable
  33458. };
  33459. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33460. };
  33461. /**
  33462. * Creates a ground mesh.
  33463. * Please consider using the same method from the MeshBuilder class instead.
  33464. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33465. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33467. */
  33468. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33469. var options = {
  33470. width: width,
  33471. height: height,
  33472. subdivisions: subdivisions,
  33473. updatable: updatable
  33474. };
  33475. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33476. };
  33477. /**
  33478. * Creates a tiled ground mesh.
  33479. * Please consider using the same method from the MeshBuilder class instead.
  33480. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33481. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33482. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33483. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33484. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33485. * numbers of subdivisions on the ground width and height of each tile.
  33486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33487. */
  33488. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33489. var options = {
  33490. xmin: xmin,
  33491. zmin: zmin,
  33492. xmax: xmax,
  33493. zmax: zmax,
  33494. subdivisions: subdivisions,
  33495. precision: precision,
  33496. updatable: updatable
  33497. };
  33498. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33499. };
  33500. /**
  33501. * Creates a ground mesh from a height map.
  33502. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33503. * Please consider using the same method from the MeshBuilder class instead.
  33504. * The parameter `url` sets the URL of the height map image resource.
  33505. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33506. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33507. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33508. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33509. * 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).
  33510. * This function is passed the newly built mesh :
  33511. * ```javascript
  33512. * function(mesh) { // do things
  33513. * return; }
  33514. * ```
  33515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33516. */
  33517. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33518. var options = {
  33519. width: width,
  33520. height: height,
  33521. subdivisions: subdivisions,
  33522. minHeight: minHeight,
  33523. maxHeight: maxHeight,
  33524. updatable: updatable,
  33525. onReady: onReady
  33526. };
  33527. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33528. };
  33529. /**
  33530. * Creates a tube mesh.
  33531. * 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.
  33532. * Please consider using the same method from the MeshBuilder class instead.
  33533. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33534. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33535. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33536. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33537. * 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.
  33538. * It must return a radius value (positive float) :
  33539. * ```javascript
  33540. * var radiusFunction = function(i, distance) {
  33541. * // do things
  33542. * return radius; }
  33543. * ```
  33544. * 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
  33545. * 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
  33546. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33547. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33548. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33549. */
  33550. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33551. var options = {
  33552. path: path,
  33553. radius: radius,
  33554. tessellation: tessellation,
  33555. radiusFunction: radiusFunction,
  33556. arc: 1,
  33557. cap: cap,
  33558. updatable: updatable,
  33559. sideOrientation: sideOrientation,
  33560. instance: instance
  33561. };
  33562. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33563. };
  33564. /**
  33565. * Creates a polyhedron mesh.
  33566. * Please consider using the same method from the MeshBuilder class instead.
  33567. * 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
  33568. * to choose the wanted type.
  33569. * The parameter `size` (positive float, default 1) sets the polygon size.
  33570. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33571. * 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`.
  33572. * 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
  33573. * 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)`).
  33574. * 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
  33575. * 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.
  33576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33577. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33579. */
  33580. Mesh.CreatePolyhedron = function (name, options, scene) {
  33581. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33582. };
  33583. /**
  33584. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33585. * Please consider using the same method from the MeshBuilder class instead.
  33586. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33587. * 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`).
  33588. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33589. * 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.
  33590. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33591. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33592. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33593. */
  33594. Mesh.CreateIcoSphere = function (name, options, scene) {
  33595. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33596. };
  33597. /**
  33598. * Creates a decal mesh.
  33599. * Please consider using the same method from the MeshBuilder class instead.
  33600. * 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.
  33601. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33602. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33603. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33604. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33605. */
  33606. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33607. var options = {
  33608. position: position,
  33609. normal: normal,
  33610. size: size,
  33611. angle: angle
  33612. };
  33613. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33614. };
  33615. // Skeletons
  33616. /**
  33617. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33618. */
  33619. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33620. if (!this._sourcePositions) {
  33621. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33622. if (!source) {
  33623. return this._sourcePositions;
  33624. }
  33625. this._sourcePositions = new Float32Array(source);
  33626. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33627. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33628. }
  33629. }
  33630. return this._sourcePositions;
  33631. };
  33632. /**
  33633. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33634. */
  33635. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33636. if (!this._sourceNormals) {
  33637. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33638. if (!source) {
  33639. return this._sourceNormals;
  33640. }
  33641. this._sourceNormals = new Float32Array(source);
  33642. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33643. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33644. }
  33645. }
  33646. return this._sourceNormals;
  33647. };
  33648. /**
  33649. * Updates the vertex buffer by applying transformation from the bones.
  33650. * Returns the Mesh.
  33651. *
  33652. * @param {skeleton} skeleton to apply
  33653. */
  33654. Mesh.prototype.applySkeleton = function (skeleton) {
  33655. if (!this.geometry) {
  33656. return this;
  33657. }
  33658. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33659. return this;
  33660. }
  33661. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33662. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33663. return this;
  33664. }
  33665. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33666. return this;
  33667. }
  33668. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33669. return this;
  33670. }
  33671. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33672. return this;
  33673. }
  33674. if (!this._sourcePositions) {
  33675. var submeshes = this.subMeshes.slice();
  33676. this.setPositionsForCPUSkinning();
  33677. this.subMeshes = submeshes;
  33678. }
  33679. if (!this._sourceNormals) {
  33680. this.setNormalsForCPUSkinning();
  33681. }
  33682. // positionsData checks for not being Float32Array will only pass at most once
  33683. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33684. if (!positionsData) {
  33685. return this;
  33686. }
  33687. if (!(positionsData instanceof Float32Array)) {
  33688. positionsData = new Float32Array(positionsData);
  33689. }
  33690. // normalsData checks for not being Float32Array will only pass at most once
  33691. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33692. if (!normalsData) {
  33693. return this;
  33694. }
  33695. if (!(normalsData instanceof Float32Array)) {
  33696. normalsData = new Float32Array(normalsData);
  33697. }
  33698. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33699. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33700. if (!matricesWeightsData || !matricesIndicesData) {
  33701. return this;
  33702. }
  33703. var needExtras = this.numBoneInfluencers > 4;
  33704. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33705. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33706. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33707. var tempVector3 = BABYLON.Vector3.Zero();
  33708. var finalMatrix = new BABYLON.Matrix();
  33709. var tempMatrix = new BABYLON.Matrix();
  33710. var matWeightIdx = 0;
  33711. var inf;
  33712. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33713. var weight;
  33714. for (inf = 0; inf < 4; inf++) {
  33715. weight = matricesWeightsData[matWeightIdx + inf];
  33716. if (weight > 0) {
  33717. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33718. finalMatrix.addToSelf(tempMatrix);
  33719. }
  33720. }
  33721. if (needExtras) {
  33722. for (inf = 0; inf < 4; inf++) {
  33723. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33724. if (weight > 0) {
  33725. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33726. finalMatrix.addToSelf(tempMatrix);
  33727. }
  33728. }
  33729. }
  33730. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33731. tempVector3.toArray(positionsData, index);
  33732. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33733. tempVector3.toArray(normalsData, index);
  33734. finalMatrix.reset();
  33735. }
  33736. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33737. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33738. return this;
  33739. };
  33740. // Tools
  33741. /**
  33742. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33743. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33744. */
  33745. Mesh.MinMax = function (meshes) {
  33746. var minVector = null;
  33747. var maxVector = null;
  33748. meshes.forEach(function (mesh, index, array) {
  33749. var boundingInfo = mesh.getBoundingInfo();
  33750. var boundingBox = boundingInfo.boundingBox;
  33751. if (!minVector || !maxVector) {
  33752. minVector = boundingBox.minimumWorld;
  33753. maxVector = boundingBox.maximumWorld;
  33754. }
  33755. else {
  33756. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33757. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33758. }
  33759. });
  33760. if (!minVector || !maxVector) {
  33761. return {
  33762. min: BABYLON.Vector3.Zero(),
  33763. max: BABYLON.Vector3.Zero()
  33764. };
  33765. }
  33766. return {
  33767. min: minVector,
  33768. max: maxVector
  33769. };
  33770. };
  33771. /**
  33772. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33773. */
  33774. Mesh.Center = function (meshesOrMinMaxVector) {
  33775. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33776. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33777. };
  33778. /**
  33779. * Merge the array of meshes into a single mesh for performance reasons.
  33780. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33781. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33782. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33783. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33784. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33785. */
  33786. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33787. if (disposeSource === void 0) { disposeSource = true; }
  33788. var index;
  33789. if (!allow32BitsIndices) {
  33790. var totalVertices = 0;
  33791. // Counting vertices
  33792. for (index = 0; index < meshes.length; index++) {
  33793. if (meshes[index]) {
  33794. totalVertices += meshes[index].getTotalVertices();
  33795. if (totalVertices > 65536) {
  33796. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33797. return null;
  33798. }
  33799. }
  33800. }
  33801. }
  33802. // Merge
  33803. var vertexData = null;
  33804. var otherVertexData;
  33805. var indiceArray = new Array();
  33806. var source = null;
  33807. for (index = 0; index < meshes.length; index++) {
  33808. if (meshes[index]) {
  33809. meshes[index].computeWorldMatrix(true);
  33810. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33811. otherVertexData.transform(meshes[index].getWorldMatrix());
  33812. if (vertexData) {
  33813. vertexData.merge(otherVertexData);
  33814. }
  33815. else {
  33816. vertexData = otherVertexData;
  33817. source = meshes[index];
  33818. }
  33819. if (subdivideWithSubMeshes) {
  33820. indiceArray.push(meshes[index].getTotalIndices());
  33821. }
  33822. }
  33823. }
  33824. source = source;
  33825. if (!meshSubclass) {
  33826. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33827. }
  33828. vertexData.applyToMesh(meshSubclass);
  33829. // Setting properties
  33830. meshSubclass.material = source.material;
  33831. meshSubclass.checkCollisions = source.checkCollisions;
  33832. // Cleaning
  33833. if (disposeSource) {
  33834. for (index = 0; index < meshes.length; index++) {
  33835. if (meshes[index]) {
  33836. meshes[index].dispose();
  33837. }
  33838. }
  33839. }
  33840. // Subdivide
  33841. if (subdivideWithSubMeshes) {
  33842. //-- removal of global submesh
  33843. meshSubclass.releaseSubMeshes();
  33844. index = 0;
  33845. var offset = 0;
  33846. //-- apply subdivision according to index table
  33847. while (index < indiceArray.length) {
  33848. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33849. offset += indiceArray[index];
  33850. index++;
  33851. }
  33852. }
  33853. return meshSubclass;
  33854. };
  33855. // Consts
  33856. Mesh._FRONTSIDE = 0;
  33857. Mesh._BACKSIDE = 1;
  33858. Mesh._DOUBLESIDE = 2;
  33859. Mesh._DEFAULTSIDE = 0;
  33860. Mesh._NO_CAP = 0;
  33861. Mesh._CAP_START = 1;
  33862. Mesh._CAP_END = 2;
  33863. Mesh._CAP_ALL = 3;
  33864. return Mesh;
  33865. }(BABYLON.AbstractMesh));
  33866. BABYLON.Mesh = Mesh;
  33867. })(BABYLON || (BABYLON = {}));
  33868. //# sourceMappingURL=babylon.mesh.js.map
  33869. var BABYLON;
  33870. (function (BABYLON) {
  33871. var BaseSubMesh = /** @class */ (function () {
  33872. function BaseSubMesh() {
  33873. }
  33874. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33875. get: function () {
  33876. return this._materialEffect;
  33877. },
  33878. enumerable: true,
  33879. configurable: true
  33880. });
  33881. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33882. if (defines === void 0) { defines = null; }
  33883. if (this._materialEffect === effect) {
  33884. if (!effect) {
  33885. this._materialDefines = null;
  33886. }
  33887. return;
  33888. }
  33889. this._materialDefines = defines;
  33890. this._materialEffect = effect;
  33891. };
  33892. return BaseSubMesh;
  33893. }());
  33894. BABYLON.BaseSubMesh = BaseSubMesh;
  33895. var SubMesh = /** @class */ (function (_super) {
  33896. __extends(SubMesh, _super);
  33897. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33898. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33899. var _this = _super.call(this) || this;
  33900. _this.materialIndex = materialIndex;
  33901. _this.verticesStart = verticesStart;
  33902. _this.verticesCount = verticesCount;
  33903. _this.indexStart = indexStart;
  33904. _this.indexCount = indexCount;
  33905. _this._renderId = 0;
  33906. _this._mesh = mesh;
  33907. _this._renderingMesh = renderingMesh || mesh;
  33908. mesh.subMeshes.push(_this);
  33909. _this._trianglePlanes = [];
  33910. _this._id = mesh.subMeshes.length - 1;
  33911. if (createBoundingBox) {
  33912. _this.refreshBoundingInfo();
  33913. mesh.computeWorldMatrix(true);
  33914. }
  33915. return _this;
  33916. }
  33917. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33918. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33919. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33920. };
  33921. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33922. get: function () {
  33923. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33924. },
  33925. enumerable: true,
  33926. configurable: true
  33927. });
  33928. /**
  33929. * Returns the submesh BoudingInfo object.
  33930. */
  33931. SubMesh.prototype.getBoundingInfo = function () {
  33932. if (this.IsGlobal) {
  33933. return this._mesh.getBoundingInfo();
  33934. }
  33935. return this._boundingInfo;
  33936. };
  33937. /**
  33938. * Sets the submesh BoundingInfo.
  33939. * Return the SubMesh.
  33940. */
  33941. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33942. this._boundingInfo = boundingInfo;
  33943. return this;
  33944. };
  33945. /**
  33946. * Returns the mesh of the current submesh.
  33947. */
  33948. SubMesh.prototype.getMesh = function () {
  33949. return this._mesh;
  33950. };
  33951. /**
  33952. * Returns the rendering mesh of the submesh.
  33953. */
  33954. SubMesh.prototype.getRenderingMesh = function () {
  33955. return this._renderingMesh;
  33956. };
  33957. /**
  33958. * Returns the submesh material.
  33959. */
  33960. SubMesh.prototype.getMaterial = function () {
  33961. var rootMaterial = this._renderingMesh.material;
  33962. if (rootMaterial === null || rootMaterial === undefined) {
  33963. return this._mesh.getScene().defaultMaterial;
  33964. }
  33965. else if (rootMaterial.getSubMaterial) {
  33966. var multiMaterial = rootMaterial;
  33967. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33968. if (this._currentMaterial !== effectiveMaterial) {
  33969. this._currentMaterial = effectiveMaterial;
  33970. this._materialDefines = null;
  33971. }
  33972. return effectiveMaterial;
  33973. }
  33974. return rootMaterial;
  33975. };
  33976. // Methods
  33977. /**
  33978. * Sets a new updated BoundingInfo object to the submesh.
  33979. * Returns the SubMesh.
  33980. */
  33981. SubMesh.prototype.refreshBoundingInfo = function () {
  33982. this._lastColliderWorldVertices = null;
  33983. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33984. return this;
  33985. }
  33986. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33987. if (!data) {
  33988. this._boundingInfo = this._mesh.getBoundingInfo();
  33989. return this;
  33990. }
  33991. var indices = this._renderingMesh.getIndices();
  33992. var extend;
  33993. //is this the only submesh?
  33994. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33995. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33996. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33997. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33998. }
  33999. else {
  34000. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34001. }
  34002. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34003. return this;
  34004. };
  34005. SubMesh.prototype._checkCollision = function (collider) {
  34006. var boundingInfo = this.getBoundingInfo();
  34007. return boundingInfo._checkCollision(collider);
  34008. };
  34009. /**
  34010. * Updates the submesh BoundingInfo.
  34011. * Returns the Submesh.
  34012. */
  34013. SubMesh.prototype.updateBoundingInfo = function (world) {
  34014. var boundingInfo = this.getBoundingInfo();
  34015. if (!boundingInfo) {
  34016. this.refreshBoundingInfo();
  34017. boundingInfo = this.getBoundingInfo();
  34018. }
  34019. boundingInfo.update(world);
  34020. return this;
  34021. };
  34022. /**
  34023. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34024. * Boolean returned.
  34025. */
  34026. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34027. var boundingInfo = this.getBoundingInfo();
  34028. if (!boundingInfo) {
  34029. return false;
  34030. }
  34031. return boundingInfo.isInFrustum(frustumPlanes);
  34032. };
  34033. /**
  34034. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34035. * Boolean returned.
  34036. */
  34037. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34038. var boundingInfo = this.getBoundingInfo();
  34039. if (!boundingInfo) {
  34040. return false;
  34041. }
  34042. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34043. };
  34044. /**
  34045. * Renders the submesh.
  34046. * Returns it.
  34047. */
  34048. SubMesh.prototype.render = function (enableAlphaMode) {
  34049. this._renderingMesh.render(this, enableAlphaMode);
  34050. return this;
  34051. };
  34052. /**
  34053. * Returns a new Index Buffer.
  34054. * Type returned : WebGLBuffer.
  34055. */
  34056. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34057. if (!this._linesIndexBuffer) {
  34058. var linesIndices = [];
  34059. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34060. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34061. }
  34062. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34063. this.linesIndexCount = linesIndices.length;
  34064. }
  34065. return this._linesIndexBuffer;
  34066. };
  34067. /**
  34068. * True is the passed Ray intersects the submesh bounding box.
  34069. * Boolean returned.
  34070. */
  34071. SubMesh.prototype.canIntersects = function (ray) {
  34072. var boundingInfo = this.getBoundingInfo();
  34073. if (!boundingInfo) {
  34074. return false;
  34075. }
  34076. return ray.intersectsBox(boundingInfo.boundingBox);
  34077. };
  34078. /**
  34079. * Returns an object IntersectionInfo.
  34080. */
  34081. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34082. var intersectInfo = null;
  34083. var material = this.getMaterial();
  34084. if (!material) {
  34085. return null;
  34086. }
  34087. switch (material.fillMode) {
  34088. case BABYLON.Material.PointListDrawMode:
  34089. case BABYLON.Material.LineListDrawMode:
  34090. case BABYLON.Material.LineLoopDrawMode:
  34091. case BABYLON.Material.LineStripDrawMode:
  34092. case BABYLON.Material.TriangleFanDrawMode:
  34093. case BABYLON.Material.TriangleStripDrawMode:
  34094. return null;
  34095. }
  34096. // LineMesh first as it's also a Mesh...
  34097. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34098. var lineMesh = this._mesh;
  34099. // Line test
  34100. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34101. var p0 = positions[indices[index]];
  34102. var p1 = positions[indices[index + 1]];
  34103. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34104. if (length < 0) {
  34105. continue;
  34106. }
  34107. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34108. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34109. if (fastCheck) {
  34110. break;
  34111. }
  34112. }
  34113. }
  34114. }
  34115. else {
  34116. // Triangles test
  34117. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34118. var p0 = positions[indices[index]];
  34119. var p1 = positions[indices[index + 1]];
  34120. var p2 = positions[indices[index + 2]];
  34121. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34122. if (currentIntersectInfo) {
  34123. if (currentIntersectInfo.distance < 0) {
  34124. continue;
  34125. }
  34126. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34127. intersectInfo = currentIntersectInfo;
  34128. intersectInfo.faceId = index / 3;
  34129. if (fastCheck) {
  34130. break;
  34131. }
  34132. }
  34133. }
  34134. }
  34135. }
  34136. return intersectInfo;
  34137. };
  34138. SubMesh.prototype._rebuild = function () {
  34139. if (this._linesIndexBuffer) {
  34140. this._linesIndexBuffer = null;
  34141. }
  34142. };
  34143. // Clone
  34144. /**
  34145. * Creates a new Submesh from the passed Mesh.
  34146. */
  34147. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34148. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34149. if (!this.IsGlobal) {
  34150. var boundingInfo = this.getBoundingInfo();
  34151. if (!boundingInfo) {
  34152. return result;
  34153. }
  34154. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34155. }
  34156. return result;
  34157. };
  34158. // Dispose
  34159. /**
  34160. * Disposes the Submesh.
  34161. * Returns nothing.
  34162. */
  34163. SubMesh.prototype.dispose = function () {
  34164. if (this._linesIndexBuffer) {
  34165. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34166. this._linesIndexBuffer = null;
  34167. }
  34168. // Remove from mesh
  34169. var index = this._mesh.subMeshes.indexOf(this);
  34170. this._mesh.subMeshes.splice(index, 1);
  34171. };
  34172. // Statics
  34173. /**
  34174. * Creates a new Submesh from the passed parameters :
  34175. * - materialIndex (integer) : the index of the main mesh material.
  34176. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34177. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34178. * - mesh (Mesh) : the main mesh to create the submesh from.
  34179. * - renderingMesh (optional Mesh) : rendering mesh.
  34180. */
  34181. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34182. var minVertexIndex = Number.MAX_VALUE;
  34183. var maxVertexIndex = -Number.MAX_VALUE;
  34184. renderingMesh = (renderingMesh || mesh);
  34185. var indices = renderingMesh.getIndices();
  34186. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34187. var vertexIndex = indices[index];
  34188. if (vertexIndex < minVertexIndex)
  34189. minVertexIndex = vertexIndex;
  34190. if (vertexIndex > maxVertexIndex)
  34191. maxVertexIndex = vertexIndex;
  34192. }
  34193. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34194. };
  34195. return SubMesh;
  34196. }(BaseSubMesh));
  34197. BABYLON.SubMesh = SubMesh;
  34198. })(BABYLON || (BABYLON = {}));
  34199. //# sourceMappingURL=babylon.subMesh.js.map
  34200. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34201. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34202. s = arguments[i];
  34203. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34204. t[p] = s[p];
  34205. }
  34206. return t;
  34207. };
  34208. var BABYLON;
  34209. (function (BABYLON) {
  34210. /**
  34211. * Manages the defines for the Material
  34212. */
  34213. var MaterialDefines = /** @class */ (function () {
  34214. function MaterialDefines() {
  34215. this._isDirty = true;
  34216. /** @hidden */
  34217. this._areLightsDirty = true;
  34218. /** @hidden */
  34219. this._areAttributesDirty = true;
  34220. /** @hidden */
  34221. this._areTexturesDirty = true;
  34222. /** @hidden */
  34223. this._areFresnelDirty = true;
  34224. /** @hidden */
  34225. this._areMiscDirty = true;
  34226. /** @hidden */
  34227. this._areImageProcessingDirty = true;
  34228. /** @hidden */
  34229. this._normals = false;
  34230. /** @hidden */
  34231. this._uvs = false;
  34232. /** @hidden */
  34233. this._needNormals = false;
  34234. /** @hidden */
  34235. this._needUVs = false;
  34236. }
  34237. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34238. /**
  34239. * Specifies if the material needs to be re-calculated
  34240. */
  34241. get: function () {
  34242. return this._isDirty;
  34243. },
  34244. enumerable: true,
  34245. configurable: true
  34246. });
  34247. /**
  34248. * Marks the material to indicate that it has been re-calculated
  34249. */
  34250. MaterialDefines.prototype.markAsProcessed = function () {
  34251. this._isDirty = false;
  34252. this._areAttributesDirty = false;
  34253. this._areTexturesDirty = false;
  34254. this._areFresnelDirty = false;
  34255. this._areLightsDirty = false;
  34256. this._areMiscDirty = false;
  34257. this._areImageProcessingDirty = false;
  34258. };
  34259. /**
  34260. * Marks the material to indicate that it needs to be re-calculated
  34261. */
  34262. MaterialDefines.prototype.markAsUnprocessed = function () {
  34263. this._isDirty = true;
  34264. };
  34265. /**
  34266. * Marks the material to indicate all of its defines need to be re-calculated
  34267. */
  34268. MaterialDefines.prototype.markAllAsDirty = function () {
  34269. this._areTexturesDirty = true;
  34270. this._areAttributesDirty = true;
  34271. this._areLightsDirty = true;
  34272. this._areFresnelDirty = true;
  34273. this._areMiscDirty = true;
  34274. this._areImageProcessingDirty = true;
  34275. this._isDirty = true;
  34276. };
  34277. /**
  34278. * Marks the material to indicate that image processing needs to be re-calculated
  34279. */
  34280. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34281. this._areImageProcessingDirty = true;
  34282. this._isDirty = true;
  34283. };
  34284. /**
  34285. * Marks the material to indicate the lights need to be re-calculated
  34286. */
  34287. MaterialDefines.prototype.markAsLightDirty = function () {
  34288. this._areLightsDirty = true;
  34289. this._isDirty = true;
  34290. };
  34291. /**
  34292. * Marks the attribute state as changed
  34293. */
  34294. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34295. this._areAttributesDirty = true;
  34296. this._isDirty = true;
  34297. };
  34298. /**
  34299. * Marks the texture state as changed
  34300. */
  34301. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34302. this._areTexturesDirty = true;
  34303. this._isDirty = true;
  34304. };
  34305. /**
  34306. * Marks the fresnel state as changed
  34307. */
  34308. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34309. this._areFresnelDirty = true;
  34310. this._isDirty = true;
  34311. };
  34312. /**
  34313. * Marks the misc state as changed
  34314. */
  34315. MaterialDefines.prototype.markAsMiscDirty = function () {
  34316. this._areMiscDirty = true;
  34317. this._isDirty = true;
  34318. };
  34319. /**
  34320. * Rebuilds the material defines
  34321. */
  34322. MaterialDefines.prototype.rebuild = function () {
  34323. if (this._keys) {
  34324. delete this._keys;
  34325. }
  34326. this._keys = [];
  34327. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34328. var key = _a[_i];
  34329. if (key[0] === "_") {
  34330. continue;
  34331. }
  34332. this._keys.push(key);
  34333. }
  34334. };
  34335. /**
  34336. * Specifies if two material defines are equal
  34337. * @param other - A material define instance to compare to
  34338. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34339. */
  34340. MaterialDefines.prototype.isEqual = function (other) {
  34341. if (this._keys.length !== other._keys.length) {
  34342. return false;
  34343. }
  34344. for (var index = 0; index < this._keys.length; index++) {
  34345. var prop = this._keys[index];
  34346. if (this[prop] !== other[prop]) {
  34347. return false;
  34348. }
  34349. }
  34350. return true;
  34351. };
  34352. /**
  34353. * Clones this instance's defines to another instance
  34354. * @param other - material defines to clone values to
  34355. */
  34356. MaterialDefines.prototype.cloneTo = function (other) {
  34357. if (this._keys.length !== other._keys.length) {
  34358. other._keys = this._keys.slice(0);
  34359. }
  34360. for (var index = 0; index < this._keys.length; index++) {
  34361. var prop = this._keys[index];
  34362. other[prop] = this[prop];
  34363. }
  34364. };
  34365. /**
  34366. * Resets the material define values
  34367. */
  34368. MaterialDefines.prototype.reset = function () {
  34369. for (var index = 0; index < this._keys.length; index++) {
  34370. var prop = this._keys[index];
  34371. var type = typeof this[prop];
  34372. switch (type) {
  34373. case "number":
  34374. this[prop] = 0;
  34375. break;
  34376. case "string":
  34377. this[prop] = "";
  34378. break;
  34379. default:
  34380. this[prop] = false;
  34381. break;
  34382. }
  34383. }
  34384. };
  34385. /**
  34386. * Converts the material define values to a string
  34387. * @returns - String of material define information
  34388. */
  34389. MaterialDefines.prototype.toString = function () {
  34390. var result = "";
  34391. for (var index = 0; index < this._keys.length; index++) {
  34392. var prop = this._keys[index];
  34393. var value = this[prop];
  34394. var type = typeof value;
  34395. switch (type) {
  34396. case "number":
  34397. case "string":
  34398. result += "#define " + prop + " " + value + "\n";
  34399. break;
  34400. default:
  34401. if (value) {
  34402. result += "#define " + prop + "\n";
  34403. }
  34404. break;
  34405. }
  34406. }
  34407. return result;
  34408. };
  34409. return MaterialDefines;
  34410. }());
  34411. BABYLON.MaterialDefines = MaterialDefines;
  34412. /**
  34413. * Base class for the main features of a material in Babylon.js
  34414. */
  34415. var Material = /** @class */ (function () {
  34416. /**
  34417. * Creates a material instance
  34418. * @param name defines the name of the material
  34419. * @param scene defines the scene to reference
  34420. * @param doNotAdd specifies if the material should be added to the scene
  34421. */
  34422. function Material(name, scene, doNotAdd) {
  34423. /**
  34424. * Specifies if the ready state should be checked on each call
  34425. */
  34426. this.checkReadyOnEveryCall = false;
  34427. /**
  34428. * Specifies if the ready state should be checked once
  34429. */
  34430. this.checkReadyOnlyOnce = false;
  34431. /**
  34432. * The state of the material
  34433. */
  34434. this.state = "";
  34435. /**
  34436. * The alpha value of the material
  34437. */
  34438. this._alpha = 1.0;
  34439. /**
  34440. * Specifies if back face culling is enabled
  34441. */
  34442. this._backFaceCulling = true;
  34443. /**
  34444. * Specifies if the material should be serialized
  34445. */
  34446. this.doNotSerialize = false;
  34447. /**
  34448. * Specifies if the effect should be stored on sub meshes
  34449. */
  34450. this.storeEffectOnSubMeshes = false;
  34451. /**
  34452. * An event triggered when the material is disposed
  34453. */
  34454. this.onDisposeObservable = new BABYLON.Observable();
  34455. /**
  34456. * An event triggered when the material is bound
  34457. */
  34458. this.onBindObservable = new BABYLON.Observable();
  34459. /**
  34460. * An event triggered when the material is unbound
  34461. */
  34462. this.onUnBindObservable = new BABYLON.Observable();
  34463. /**
  34464. * Stores the value of the alpha mode
  34465. */
  34466. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34467. /**
  34468. * Stores the state of the need depth pre-pass value
  34469. */
  34470. this._needDepthPrePass = false;
  34471. /**
  34472. * Specifies if depth writing should be disabled
  34473. */
  34474. this.disableDepthWrite = false;
  34475. /**
  34476. * Specifies if depth writing should be forced
  34477. */
  34478. this.forceDepthWrite = false;
  34479. /**
  34480. * Specifies if there should be a separate pass for culling
  34481. */
  34482. this.separateCullingPass = false;
  34483. /**
  34484. * Stores the state specifing if fog should be enabled
  34485. */
  34486. this._fogEnabled = true;
  34487. /**
  34488. * Stores the size of points
  34489. */
  34490. this.pointSize = 1.0;
  34491. /**
  34492. * Stores the z offset value
  34493. */
  34494. this.zOffset = 0;
  34495. /**
  34496. * Specifies if the material was previously ready
  34497. */
  34498. this._wasPreviouslyReady = false;
  34499. /**
  34500. * Stores the fill mode state
  34501. */
  34502. this._fillMode = Material.TriangleFillMode;
  34503. this.name = name;
  34504. this.id = name || BABYLON.Tools.RandomId();
  34505. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34506. this.uniqueId = this._scene.getUniqueId();
  34507. if (this._scene.useRightHandedSystem) {
  34508. this.sideOrientation = Material.ClockWiseSideOrientation;
  34509. }
  34510. else {
  34511. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34512. }
  34513. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34514. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34515. if (!doNotAdd) {
  34516. this._scene.materials.push(this);
  34517. }
  34518. }
  34519. Object.defineProperty(Material, "TriangleFillMode", {
  34520. /**
  34521. * Returns the triangle fill mode
  34522. */
  34523. get: function () {
  34524. return Material._TriangleFillMode;
  34525. },
  34526. enumerable: true,
  34527. configurable: true
  34528. });
  34529. Object.defineProperty(Material, "WireFrameFillMode", {
  34530. /**
  34531. * Returns the wireframe mode
  34532. */
  34533. get: function () {
  34534. return Material._WireFrameFillMode;
  34535. },
  34536. enumerable: true,
  34537. configurable: true
  34538. });
  34539. Object.defineProperty(Material, "PointFillMode", {
  34540. /**
  34541. * Returns the point fill mode
  34542. */
  34543. get: function () {
  34544. return Material._PointFillMode;
  34545. },
  34546. enumerable: true,
  34547. configurable: true
  34548. });
  34549. Object.defineProperty(Material, "PointListDrawMode", {
  34550. /**
  34551. * Returns the point list draw mode
  34552. */
  34553. get: function () {
  34554. return Material._PointListDrawMode;
  34555. },
  34556. enumerable: true,
  34557. configurable: true
  34558. });
  34559. Object.defineProperty(Material, "LineListDrawMode", {
  34560. /**
  34561. * Returns the line list draw mode
  34562. */
  34563. get: function () {
  34564. return Material._LineListDrawMode;
  34565. },
  34566. enumerable: true,
  34567. configurable: true
  34568. });
  34569. Object.defineProperty(Material, "LineLoopDrawMode", {
  34570. /**
  34571. * Returns the line loop draw mode
  34572. */
  34573. get: function () {
  34574. return Material._LineLoopDrawMode;
  34575. },
  34576. enumerable: true,
  34577. configurable: true
  34578. });
  34579. Object.defineProperty(Material, "LineStripDrawMode", {
  34580. /**
  34581. * Returns the line strip draw mode
  34582. */
  34583. get: function () {
  34584. return Material._LineStripDrawMode;
  34585. },
  34586. enumerable: true,
  34587. configurable: true
  34588. });
  34589. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34590. /**
  34591. * Returns the triangle strip draw mode
  34592. */
  34593. get: function () {
  34594. return Material._TriangleStripDrawMode;
  34595. },
  34596. enumerable: true,
  34597. configurable: true
  34598. });
  34599. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34600. /**
  34601. * Returns the triangle fan draw mode
  34602. */
  34603. get: function () {
  34604. return Material._TriangleFanDrawMode;
  34605. },
  34606. enumerable: true,
  34607. configurable: true
  34608. });
  34609. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34610. /**
  34611. * Returns the clock-wise side orientation
  34612. */
  34613. get: function () {
  34614. return Material._ClockWiseSideOrientation;
  34615. },
  34616. enumerable: true,
  34617. configurable: true
  34618. });
  34619. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34620. /**
  34621. * Returns the counter clock-wise side orientation
  34622. */
  34623. get: function () {
  34624. return Material._CounterClockWiseSideOrientation;
  34625. },
  34626. enumerable: true,
  34627. configurable: true
  34628. });
  34629. Object.defineProperty(Material, "TextureDirtyFlag", {
  34630. /**
  34631. * Returns the dirty texture flag value
  34632. */
  34633. get: function () {
  34634. return Material._TextureDirtyFlag;
  34635. },
  34636. enumerable: true,
  34637. configurable: true
  34638. });
  34639. Object.defineProperty(Material, "LightDirtyFlag", {
  34640. /**
  34641. * Returns the dirty light flag value
  34642. */
  34643. get: function () {
  34644. return Material._LightDirtyFlag;
  34645. },
  34646. enumerable: true,
  34647. configurable: true
  34648. });
  34649. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34650. /**
  34651. * Returns the dirty fresnel flag value
  34652. */
  34653. get: function () {
  34654. return Material._FresnelDirtyFlag;
  34655. },
  34656. enumerable: true,
  34657. configurable: true
  34658. });
  34659. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34660. /**
  34661. * Returns the dirty attributes flag value
  34662. */
  34663. get: function () {
  34664. return Material._AttributesDirtyFlag;
  34665. },
  34666. enumerable: true,
  34667. configurable: true
  34668. });
  34669. Object.defineProperty(Material, "MiscDirtyFlag", {
  34670. /**
  34671. * Returns the dirty misc flag value
  34672. */
  34673. get: function () {
  34674. return Material._MiscDirtyFlag;
  34675. },
  34676. enumerable: true,
  34677. configurable: true
  34678. });
  34679. Object.defineProperty(Material.prototype, "alpha", {
  34680. /**
  34681. * Gets the alpha value of the material
  34682. */
  34683. get: function () {
  34684. return this._alpha;
  34685. },
  34686. /**
  34687. * Sets the alpha value of the material
  34688. */
  34689. set: function (value) {
  34690. if (this._alpha === value) {
  34691. return;
  34692. }
  34693. this._alpha = value;
  34694. this.markAsDirty(Material.MiscDirtyFlag);
  34695. },
  34696. enumerable: true,
  34697. configurable: true
  34698. });
  34699. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34700. /**
  34701. * Gets the back-face culling state
  34702. */
  34703. get: function () {
  34704. return this._backFaceCulling;
  34705. },
  34706. /**
  34707. * Sets the back-face culling state
  34708. */
  34709. set: function (value) {
  34710. if (this._backFaceCulling === value) {
  34711. return;
  34712. }
  34713. this._backFaceCulling = value;
  34714. this.markAsDirty(Material.TextureDirtyFlag);
  34715. },
  34716. enumerable: true,
  34717. configurable: true
  34718. });
  34719. Object.defineProperty(Material.prototype, "onDispose", {
  34720. /**
  34721. * Called during a dispose event
  34722. */
  34723. set: function (callback) {
  34724. if (this._onDisposeObserver) {
  34725. this.onDisposeObservable.remove(this._onDisposeObserver);
  34726. }
  34727. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34728. },
  34729. enumerable: true,
  34730. configurable: true
  34731. });
  34732. Object.defineProperty(Material.prototype, "onBind", {
  34733. /**
  34734. * Called during a bind event
  34735. */
  34736. set: function (callback) {
  34737. if (this._onBindObserver) {
  34738. this.onBindObservable.remove(this._onBindObserver);
  34739. }
  34740. this._onBindObserver = this.onBindObservable.add(callback);
  34741. },
  34742. enumerable: true,
  34743. configurable: true
  34744. });
  34745. Object.defineProperty(Material.prototype, "alphaMode", {
  34746. /**
  34747. * Gets the value of the alpha mode
  34748. */
  34749. get: function () {
  34750. return this._alphaMode;
  34751. },
  34752. /**
  34753. * Sets the value of the alpha mode.
  34754. *
  34755. * | Value | Type | Description |
  34756. * | --- | --- | --- |
  34757. * | 0 | ALPHA_DISABLE | |
  34758. * | 1 | ALPHA_ADD | |
  34759. * | 2 | ALPHA_COMBINE | |
  34760. * | 3 | ALPHA_SUBTRACT | |
  34761. * | 4 | ALPHA_MULTIPLY | |
  34762. * | 5 | ALPHA_MAXIMIZED | |
  34763. * | 6 | ALPHA_ONEONE | |
  34764. * | 7 | ALPHA_PREMULTIPLIED | |
  34765. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34766. * | 9 | ALPHA_INTERPOLATE | |
  34767. * | 10 | ALPHA_SCREENMODE | |
  34768. *
  34769. */
  34770. set: function (value) {
  34771. if (this._alphaMode === value) {
  34772. return;
  34773. }
  34774. this._alphaMode = value;
  34775. this.markAsDirty(Material.TextureDirtyFlag);
  34776. },
  34777. enumerable: true,
  34778. configurable: true
  34779. });
  34780. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34781. /**
  34782. * Gets the depth pre-pass value
  34783. */
  34784. get: function () {
  34785. return this._needDepthPrePass;
  34786. },
  34787. /**
  34788. * Sets the need depth pre-pass value
  34789. */
  34790. set: function (value) {
  34791. if (this._needDepthPrePass === value) {
  34792. return;
  34793. }
  34794. this._needDepthPrePass = value;
  34795. if (this._needDepthPrePass) {
  34796. this.checkReadyOnEveryCall = true;
  34797. }
  34798. },
  34799. enumerable: true,
  34800. configurable: true
  34801. });
  34802. Object.defineProperty(Material.prototype, "fogEnabled", {
  34803. /**
  34804. * Gets the value of the fog enabled state
  34805. */
  34806. get: function () {
  34807. return this._fogEnabled;
  34808. },
  34809. /**
  34810. * Sets the state for enabling fog
  34811. */
  34812. set: function (value) {
  34813. if (this._fogEnabled === value) {
  34814. return;
  34815. }
  34816. this._fogEnabled = value;
  34817. this.markAsDirty(Material.MiscDirtyFlag);
  34818. },
  34819. enumerable: true,
  34820. configurable: true
  34821. });
  34822. Object.defineProperty(Material.prototype, "wireframe", {
  34823. /**
  34824. * Gets a value specifying if wireframe mode is enabled
  34825. */
  34826. get: function () {
  34827. switch (this._fillMode) {
  34828. case Material.WireFrameFillMode:
  34829. case Material.LineListDrawMode:
  34830. case Material.LineLoopDrawMode:
  34831. case Material.LineStripDrawMode:
  34832. return true;
  34833. }
  34834. return this._scene.forceWireframe;
  34835. },
  34836. /**
  34837. * Sets the state of wireframe mode
  34838. */
  34839. set: function (value) {
  34840. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34841. },
  34842. enumerable: true,
  34843. configurable: true
  34844. });
  34845. Object.defineProperty(Material.prototype, "pointsCloud", {
  34846. /**
  34847. * Gets the value specifying if point clouds are enabled
  34848. */
  34849. get: function () {
  34850. switch (this._fillMode) {
  34851. case Material.PointFillMode:
  34852. case Material.PointListDrawMode:
  34853. return true;
  34854. }
  34855. return this._scene.forcePointsCloud;
  34856. },
  34857. /**
  34858. * Sets the state of point cloud mode
  34859. */
  34860. set: function (value) {
  34861. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34862. },
  34863. enumerable: true,
  34864. configurable: true
  34865. });
  34866. Object.defineProperty(Material.prototype, "fillMode", {
  34867. /**
  34868. * Gets the material fill mode
  34869. */
  34870. get: function () {
  34871. return this._fillMode;
  34872. },
  34873. /**
  34874. * Sets the material fill mode
  34875. */
  34876. set: function (value) {
  34877. if (this._fillMode === value) {
  34878. return;
  34879. }
  34880. this._fillMode = value;
  34881. this.markAsDirty(Material.MiscDirtyFlag);
  34882. },
  34883. enumerable: true,
  34884. configurable: true
  34885. });
  34886. /**
  34887. * Returns a string representation of the current material
  34888. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34889. * @returns a string with material information
  34890. */
  34891. Material.prototype.toString = function (fullDetails) {
  34892. var ret = "Name: " + this.name;
  34893. if (fullDetails) {
  34894. }
  34895. return ret;
  34896. };
  34897. /**
  34898. * Gets the class name of the material
  34899. * @returns a string with the class name of the material
  34900. */
  34901. Material.prototype.getClassName = function () {
  34902. return "Material";
  34903. };
  34904. Object.defineProperty(Material.prototype, "isFrozen", {
  34905. /**
  34906. * Specifies if updates for the material been locked
  34907. */
  34908. get: function () {
  34909. return this.checkReadyOnlyOnce;
  34910. },
  34911. enumerable: true,
  34912. configurable: true
  34913. });
  34914. /**
  34915. * Locks updates for the material
  34916. */
  34917. Material.prototype.freeze = function () {
  34918. this.checkReadyOnlyOnce = true;
  34919. };
  34920. /**
  34921. * Unlocks updates for the material
  34922. */
  34923. Material.prototype.unfreeze = function () {
  34924. this.checkReadyOnlyOnce = false;
  34925. };
  34926. /**
  34927. * Specifies if the material is ready to be used
  34928. * @param mesh defines the mesh to check
  34929. * @param useInstances specifies if instances should be used
  34930. * @returns a boolean indicating if the material is ready to be used
  34931. */
  34932. Material.prototype.isReady = function (mesh, useInstances) {
  34933. return true;
  34934. };
  34935. /**
  34936. * Specifies that the submesh is ready to be used
  34937. * @param mesh defines the mesh to check
  34938. * @param subMesh defines which submesh to check
  34939. * @param useInstances specifies that instances should be used
  34940. * @returns a boolean indicating that the submesh is ready or not
  34941. */
  34942. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34943. return false;
  34944. };
  34945. /**
  34946. * Returns the material effect
  34947. * @returns the effect associated with the material
  34948. */
  34949. Material.prototype.getEffect = function () {
  34950. return this._effect;
  34951. };
  34952. /**
  34953. * Returns the current scene
  34954. * @returns a Scene
  34955. */
  34956. Material.prototype.getScene = function () {
  34957. return this._scene;
  34958. };
  34959. /**
  34960. * Specifies if the material will require alpha blending
  34961. * @returns a boolean specifying if alpha blending is needed
  34962. */
  34963. Material.prototype.needAlphaBlending = function () {
  34964. return (this.alpha < 1.0);
  34965. };
  34966. /**
  34967. * Specifies if the mesh will require alpha blending
  34968. * @param mesh defines the mesh to check
  34969. * @returns a boolean specifying if alpha blending is needed for the mesh
  34970. */
  34971. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34972. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34973. };
  34974. /**
  34975. * Specifies if this material should be rendered in alpha test mode
  34976. * @returns a boolean specifying if an alpha test is needed.
  34977. */
  34978. Material.prototype.needAlphaTesting = function () {
  34979. return false;
  34980. };
  34981. /**
  34982. * Gets the texture used for the alpha test
  34983. * @returns the texture to use for alpha testing
  34984. */
  34985. Material.prototype.getAlphaTestTexture = function () {
  34986. return null;
  34987. };
  34988. /**
  34989. * Marks the material to indicate that it needs to be re-calculated
  34990. */
  34991. Material.prototype.markDirty = function () {
  34992. this._wasPreviouslyReady = false;
  34993. };
  34994. /** @hidden */
  34995. Material.prototype._preBind = function (effect, overrideOrientation) {
  34996. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34997. var engine = this._scene.getEngine();
  34998. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34999. var reverse = orientation === Material.ClockWiseSideOrientation;
  35000. engine.enableEffect(effect ? effect : this._effect);
  35001. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35002. return reverse;
  35003. };
  35004. /**
  35005. * Binds the material to the mesh
  35006. * @param world defines the world transformation matrix
  35007. * @param mesh defines the mesh to bind the material to
  35008. */
  35009. Material.prototype.bind = function (world, mesh) {
  35010. };
  35011. /**
  35012. * Binds the submesh to the material
  35013. * @param world defines the world transformation matrix
  35014. * @param mesh defines the mesh containing the submesh
  35015. * @param subMesh defines the submesh to bind the material to
  35016. */
  35017. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35018. };
  35019. /**
  35020. * Binds the world matrix to the material
  35021. * @param world defines the world transformation matrix
  35022. */
  35023. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35024. };
  35025. /**
  35026. * Binds the scene's uniform buffer to the effect.
  35027. * @param effect defines the effect to bind to the scene uniform buffer
  35028. * @param sceneUbo defines the uniform buffer storing scene data
  35029. */
  35030. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35031. sceneUbo.bindToEffect(effect, "Scene");
  35032. };
  35033. /**
  35034. * Binds the view matrix to the effect
  35035. * @param effect defines the effect to bind the view matrix to
  35036. */
  35037. Material.prototype.bindView = function (effect) {
  35038. if (!this._useUBO) {
  35039. effect.setMatrix("view", this.getScene().getViewMatrix());
  35040. }
  35041. else {
  35042. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35043. }
  35044. };
  35045. /**
  35046. * Binds the view projection matrix to the effect
  35047. * @param effect defines the effect to bind the view projection matrix to
  35048. */
  35049. Material.prototype.bindViewProjection = function (effect) {
  35050. if (!this._useUBO) {
  35051. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35052. }
  35053. else {
  35054. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35055. }
  35056. };
  35057. /**
  35058. * Specifies if material alpha testing should be turned on for the mesh
  35059. * @param mesh defines the mesh to check
  35060. */
  35061. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35062. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35063. };
  35064. /**
  35065. * Processes to execute after binding the material to a mesh
  35066. * @param mesh defines the rendered mesh
  35067. */
  35068. Material.prototype._afterBind = function (mesh) {
  35069. this._scene._cachedMaterial = this;
  35070. if (mesh) {
  35071. this._scene._cachedVisibility = mesh.visibility;
  35072. }
  35073. else {
  35074. this._scene._cachedVisibility = 1;
  35075. }
  35076. if (mesh) {
  35077. this.onBindObservable.notifyObservers(mesh);
  35078. }
  35079. if (this.disableDepthWrite) {
  35080. var engine = this._scene.getEngine();
  35081. this._cachedDepthWriteState = engine.getDepthWrite();
  35082. engine.setDepthWrite(false);
  35083. }
  35084. };
  35085. /**
  35086. * Unbinds the material from the mesh
  35087. */
  35088. Material.prototype.unbind = function () {
  35089. this.onUnBindObservable.notifyObservers(this);
  35090. if (this.disableDepthWrite) {
  35091. var engine = this._scene.getEngine();
  35092. engine.setDepthWrite(this._cachedDepthWriteState);
  35093. }
  35094. };
  35095. /**
  35096. * Gets the active textures from the material
  35097. * @returns an array of textures
  35098. */
  35099. Material.prototype.getActiveTextures = function () {
  35100. return [];
  35101. };
  35102. /**
  35103. * Specifies if the material uses a texture
  35104. * @param texture defines the texture to check against the material
  35105. * @returns a boolean specifying if the material uses the texture
  35106. */
  35107. Material.prototype.hasTexture = function (texture) {
  35108. return false;
  35109. };
  35110. /**
  35111. * Makes a duplicate of the material, and gives it a new name
  35112. * @param name defines the new name for the duplicated material
  35113. * @returns the cloned material
  35114. */
  35115. Material.prototype.clone = function (name) {
  35116. return null;
  35117. };
  35118. /**
  35119. * Gets the meshes bound to the material
  35120. * @returns an array of meshes bound to the material
  35121. */
  35122. Material.prototype.getBindedMeshes = function () {
  35123. var result = new Array();
  35124. for (var index = 0; index < this._scene.meshes.length; index++) {
  35125. var mesh = this._scene.meshes[index];
  35126. if (mesh.material === this) {
  35127. result.push(mesh);
  35128. }
  35129. }
  35130. return result;
  35131. };
  35132. /**
  35133. * Force shader compilation
  35134. * @param mesh defines the mesh associated with this material
  35135. * @param onCompiled defines a function to execute once the material is compiled
  35136. * @param options defines the options to configure the compilation
  35137. */
  35138. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35139. var _this = this;
  35140. var localOptions = __assign({ clipPlane: false }, options);
  35141. var subMesh = new BABYLON.BaseSubMesh();
  35142. var scene = this.getScene();
  35143. var checkReady = function () {
  35144. if (!_this._scene || !_this._scene.getEngine()) {
  35145. return;
  35146. }
  35147. if (subMesh._materialDefines) {
  35148. subMesh._materialDefines._renderId = -1;
  35149. }
  35150. var clipPlaneState = scene.clipPlane;
  35151. if (localOptions.clipPlane) {
  35152. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35153. }
  35154. if (_this.storeEffectOnSubMeshes) {
  35155. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35156. if (onCompiled) {
  35157. onCompiled(_this);
  35158. }
  35159. }
  35160. else {
  35161. setTimeout(checkReady, 16);
  35162. }
  35163. }
  35164. else {
  35165. if (_this.isReady(mesh)) {
  35166. if (onCompiled) {
  35167. onCompiled(_this);
  35168. }
  35169. }
  35170. else {
  35171. setTimeout(checkReady, 16);
  35172. }
  35173. }
  35174. if (localOptions.clipPlane) {
  35175. scene.clipPlane = clipPlaneState;
  35176. }
  35177. };
  35178. checkReady();
  35179. };
  35180. /**
  35181. * Force shader compilation
  35182. * @param mesh defines the mesh that will use this material
  35183. * @param options defines additional options for compiling the shaders
  35184. * @returns a promise that resolves when the compilation completes
  35185. */
  35186. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35187. var _this = this;
  35188. return new Promise(function (resolve) {
  35189. _this.forceCompilation(mesh, function () {
  35190. resolve();
  35191. }, options);
  35192. });
  35193. };
  35194. /**
  35195. * Marks a define in the material to indicate that it needs to be re-computed
  35196. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35197. */
  35198. Material.prototype.markAsDirty = function (flag) {
  35199. if (flag & Material.TextureDirtyFlag) {
  35200. this._markAllSubMeshesAsTexturesDirty();
  35201. }
  35202. if (flag & Material.LightDirtyFlag) {
  35203. this._markAllSubMeshesAsLightsDirty();
  35204. }
  35205. if (flag & Material.FresnelDirtyFlag) {
  35206. this._markAllSubMeshesAsFresnelDirty();
  35207. }
  35208. if (flag & Material.AttributesDirtyFlag) {
  35209. this._markAllSubMeshesAsAttributesDirty();
  35210. }
  35211. if (flag & Material.MiscDirtyFlag) {
  35212. this._markAllSubMeshesAsMiscDirty();
  35213. }
  35214. this.getScene().resetCachedMaterial();
  35215. };
  35216. /**
  35217. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35218. * @param func defines a function which checks material defines against the submeshes
  35219. */
  35220. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35221. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35222. var mesh = _a[_i];
  35223. if (!mesh.subMeshes) {
  35224. continue;
  35225. }
  35226. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35227. var subMesh = _c[_b];
  35228. if (subMesh.getMaterial() !== this) {
  35229. continue;
  35230. }
  35231. if (!subMesh._materialDefines) {
  35232. continue;
  35233. }
  35234. func(subMesh._materialDefines);
  35235. }
  35236. }
  35237. };
  35238. /**
  35239. * Indicates that image processing needs to be re-calculated for all submeshes
  35240. */
  35241. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35242. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35243. };
  35244. /**
  35245. * Indicates that textures need to be re-calculated for all submeshes
  35246. */
  35247. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35248. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35249. };
  35250. /**
  35251. * Indicates that fresnel needs to be re-calculated for all submeshes
  35252. */
  35253. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35254. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35255. };
  35256. /**
  35257. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35258. */
  35259. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35260. this._markAllSubMeshesAsDirty(function (defines) {
  35261. defines.markAsFresnelDirty();
  35262. defines.markAsMiscDirty();
  35263. });
  35264. };
  35265. /**
  35266. * Indicates that lights need to be re-calculated for all submeshes
  35267. */
  35268. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35269. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35270. };
  35271. /**
  35272. * Indicates that attributes need to be re-calculated for all submeshes
  35273. */
  35274. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35275. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35276. };
  35277. /**
  35278. * Indicates that misc needs to be re-calculated for all submeshes
  35279. */
  35280. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35281. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35282. };
  35283. /**
  35284. * Indicates that textures and misc need to be re-calculated for all submeshes
  35285. */
  35286. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35287. this._markAllSubMeshesAsDirty(function (defines) {
  35288. defines.markAsTexturesDirty();
  35289. defines.markAsMiscDirty();
  35290. });
  35291. };
  35292. /**
  35293. * Disposes the material
  35294. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35295. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35296. */
  35297. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35298. // Animations
  35299. this.getScene().stopAnimation(this);
  35300. this.getScene().freeProcessedMaterials();
  35301. // Remove from scene
  35302. var index = this._scene.materials.indexOf(this);
  35303. if (index >= 0) {
  35304. this._scene.materials.splice(index, 1);
  35305. }
  35306. // Remove from meshes
  35307. for (index = 0; index < this._scene.meshes.length; index++) {
  35308. var mesh = this._scene.meshes[index];
  35309. if (mesh.material === this) {
  35310. mesh.material = null;
  35311. if (mesh.geometry) {
  35312. var geometry = (mesh.geometry);
  35313. if (this.storeEffectOnSubMeshes) {
  35314. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35315. var subMesh = _a[_i];
  35316. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35317. if (forceDisposeEffect && subMesh._materialEffect) {
  35318. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35319. }
  35320. }
  35321. }
  35322. else {
  35323. geometry._releaseVertexArrayObject(this._effect);
  35324. }
  35325. }
  35326. }
  35327. }
  35328. this._uniformBuffer.dispose();
  35329. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35330. if (forceDisposeEffect && this._effect) {
  35331. if (!this.storeEffectOnSubMeshes) {
  35332. this._scene.getEngine()._releaseEffect(this._effect);
  35333. }
  35334. this._effect = null;
  35335. }
  35336. // Callback
  35337. this.onDisposeObservable.notifyObservers(this);
  35338. this.onDisposeObservable.clear();
  35339. this.onBindObservable.clear();
  35340. this.onUnBindObservable.clear();
  35341. };
  35342. /**
  35343. * Serializes this material
  35344. * @returns the serialized material object
  35345. */
  35346. Material.prototype.serialize = function () {
  35347. return BABYLON.SerializationHelper.Serialize(this);
  35348. };
  35349. /**
  35350. * Creates a MultiMaterial from parsed MultiMaterial data.
  35351. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35352. * @param scene defines the hosting scene
  35353. * @returns a new MultiMaterial
  35354. */
  35355. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35356. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35357. multiMaterial.id = parsedMultiMaterial.id;
  35358. if (BABYLON.Tags) {
  35359. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35360. }
  35361. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35362. var subMatId = parsedMultiMaterial.materials[matIndex];
  35363. if (subMatId) {
  35364. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35365. }
  35366. else {
  35367. multiMaterial.subMaterials.push(null);
  35368. }
  35369. }
  35370. return multiMaterial;
  35371. };
  35372. /**
  35373. * Creates a material from parsed material data
  35374. * @param parsedMaterial defines parsed material data
  35375. * @param scene defines the hosting scene
  35376. * @param rootUrl defines the root URL to use to load textures
  35377. * @returns a new material
  35378. */
  35379. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35380. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35381. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35382. }
  35383. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35384. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35385. if (!BABYLON.LegacyPBRMaterial) {
  35386. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35387. return;
  35388. }
  35389. }
  35390. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35391. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35392. };
  35393. // Triangle views
  35394. Material._TriangleFillMode = 0;
  35395. Material._WireFrameFillMode = 1;
  35396. Material._PointFillMode = 2;
  35397. // Draw modes
  35398. Material._PointListDrawMode = 3;
  35399. Material._LineListDrawMode = 4;
  35400. Material._LineLoopDrawMode = 5;
  35401. Material._LineStripDrawMode = 6;
  35402. Material._TriangleStripDrawMode = 7;
  35403. Material._TriangleFanDrawMode = 8;
  35404. /**
  35405. * Stores the clock-wise side orientation
  35406. */
  35407. Material._ClockWiseSideOrientation = 0;
  35408. /**
  35409. * Stores the counter clock-wise side orientation
  35410. */
  35411. Material._CounterClockWiseSideOrientation = 1;
  35412. /**
  35413. * The dirty texture flag value
  35414. */
  35415. Material._TextureDirtyFlag = 1;
  35416. /**
  35417. * The dirty light flag value
  35418. */
  35419. Material._LightDirtyFlag = 2;
  35420. /**
  35421. * The dirty fresnel flag value
  35422. */
  35423. Material._FresnelDirtyFlag = 4;
  35424. /**
  35425. * The dirty attribute flag value
  35426. */
  35427. Material._AttributesDirtyFlag = 8;
  35428. /**
  35429. * The dirty misc flag value
  35430. */
  35431. Material._MiscDirtyFlag = 16;
  35432. __decorate([
  35433. BABYLON.serialize()
  35434. ], Material.prototype, "id", void 0);
  35435. __decorate([
  35436. BABYLON.serialize()
  35437. ], Material.prototype, "uniqueId", void 0);
  35438. __decorate([
  35439. BABYLON.serialize()
  35440. ], Material.prototype, "name", void 0);
  35441. __decorate([
  35442. BABYLON.serialize()
  35443. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35444. __decorate([
  35445. BABYLON.serialize()
  35446. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35447. __decorate([
  35448. BABYLON.serialize()
  35449. ], Material.prototype, "state", void 0);
  35450. __decorate([
  35451. BABYLON.serialize("alpha")
  35452. ], Material.prototype, "_alpha", void 0);
  35453. __decorate([
  35454. BABYLON.serialize("backFaceCulling")
  35455. ], Material.prototype, "_backFaceCulling", void 0);
  35456. __decorate([
  35457. BABYLON.serialize()
  35458. ], Material.prototype, "sideOrientation", void 0);
  35459. __decorate([
  35460. BABYLON.serialize("alphaMode")
  35461. ], Material.prototype, "_alphaMode", void 0);
  35462. __decorate([
  35463. BABYLON.serialize()
  35464. ], Material.prototype, "_needDepthPrePass", void 0);
  35465. __decorate([
  35466. BABYLON.serialize()
  35467. ], Material.prototype, "disableDepthWrite", void 0);
  35468. __decorate([
  35469. BABYLON.serialize()
  35470. ], Material.prototype, "forceDepthWrite", void 0);
  35471. __decorate([
  35472. BABYLON.serialize()
  35473. ], Material.prototype, "separateCullingPass", void 0);
  35474. __decorate([
  35475. BABYLON.serialize("fogEnabled")
  35476. ], Material.prototype, "_fogEnabled", void 0);
  35477. __decorate([
  35478. BABYLON.serialize()
  35479. ], Material.prototype, "pointSize", void 0);
  35480. __decorate([
  35481. BABYLON.serialize()
  35482. ], Material.prototype, "zOffset", void 0);
  35483. __decorate([
  35484. BABYLON.serialize()
  35485. ], Material.prototype, "wireframe", null);
  35486. __decorate([
  35487. BABYLON.serialize()
  35488. ], Material.prototype, "pointsCloud", null);
  35489. __decorate([
  35490. BABYLON.serialize()
  35491. ], Material.prototype, "fillMode", null);
  35492. return Material;
  35493. }());
  35494. BABYLON.Material = Material;
  35495. })(BABYLON || (BABYLON = {}));
  35496. //# sourceMappingURL=babylon.material.js.map
  35497. var BABYLON;
  35498. (function (BABYLON) {
  35499. var UniformBuffer = /** @class */ (function () {
  35500. /**
  35501. * Uniform buffer objects.
  35502. *
  35503. * Handles blocks of uniform on the GPU.
  35504. *
  35505. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35506. *
  35507. * For more information, please refer to :
  35508. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35509. */
  35510. function UniformBuffer(engine, data, dynamic) {
  35511. this._engine = engine;
  35512. this._noUBO = !engine.supportsUniformBuffers;
  35513. this._dynamic = dynamic;
  35514. this._data = data || [];
  35515. this._uniformLocations = {};
  35516. this._uniformSizes = {};
  35517. this._uniformLocationPointer = 0;
  35518. this._needSync = false;
  35519. if (this._noUBO) {
  35520. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35521. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35522. this.updateFloat = this._updateFloatForEffect;
  35523. this.updateFloat2 = this._updateFloat2ForEffect;
  35524. this.updateFloat3 = this._updateFloat3ForEffect;
  35525. this.updateFloat4 = this._updateFloat4ForEffect;
  35526. this.updateMatrix = this._updateMatrixForEffect;
  35527. this.updateVector3 = this._updateVector3ForEffect;
  35528. this.updateVector4 = this._updateVector4ForEffect;
  35529. this.updateColor3 = this._updateColor3ForEffect;
  35530. this.updateColor4 = this._updateColor4ForEffect;
  35531. }
  35532. else {
  35533. this._engine._uniformBuffers.push(this);
  35534. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35535. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35536. this.updateFloat = this._updateFloatForUniform;
  35537. this.updateFloat2 = this._updateFloat2ForUniform;
  35538. this.updateFloat3 = this._updateFloat3ForUniform;
  35539. this.updateFloat4 = this._updateFloat4ForUniform;
  35540. this.updateMatrix = this._updateMatrixForUniform;
  35541. this.updateVector3 = this._updateVector3ForUniform;
  35542. this.updateVector4 = this._updateVector4ForUniform;
  35543. this.updateColor3 = this._updateColor3ForUniform;
  35544. this.updateColor4 = this._updateColor4ForUniform;
  35545. }
  35546. }
  35547. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35548. // Properties
  35549. /**
  35550. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35551. * or just falling back on setUniformXXX calls.
  35552. */
  35553. get: function () {
  35554. return !this._noUBO;
  35555. },
  35556. enumerable: true,
  35557. configurable: true
  35558. });
  35559. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35560. /**
  35561. * Indicates if the WebGL underlying uniform buffer is in sync
  35562. * with the javascript cache data.
  35563. */
  35564. get: function () {
  35565. return !this._needSync;
  35566. },
  35567. enumerable: true,
  35568. configurable: true
  35569. });
  35570. /**
  35571. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35572. * Also, a dynamic UniformBuffer will disable cache verification and always
  35573. * update the underlying WebGL uniform buffer to the GPU.
  35574. */
  35575. UniformBuffer.prototype.isDynamic = function () {
  35576. return this._dynamic !== undefined;
  35577. };
  35578. /**
  35579. * The data cache on JS side.
  35580. */
  35581. UniformBuffer.prototype.getData = function () {
  35582. return this._bufferData;
  35583. };
  35584. /**
  35585. * The underlying WebGL Uniform buffer.
  35586. */
  35587. UniformBuffer.prototype.getBuffer = function () {
  35588. return this._buffer;
  35589. };
  35590. /**
  35591. * std140 layout specifies how to align data within an UBO structure.
  35592. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35593. * for specs.
  35594. */
  35595. UniformBuffer.prototype._fillAlignment = function (size) {
  35596. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35597. // and 4x4 matrices
  35598. // TODO : change if other types are used
  35599. var alignment;
  35600. if (size <= 2) {
  35601. alignment = size;
  35602. }
  35603. else {
  35604. alignment = 4;
  35605. }
  35606. if ((this._uniformLocationPointer % alignment) !== 0) {
  35607. var oldPointer = this._uniformLocationPointer;
  35608. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35609. var diff = this._uniformLocationPointer - oldPointer;
  35610. for (var i = 0; i < diff; i++) {
  35611. this._data.push(0);
  35612. }
  35613. }
  35614. };
  35615. /**
  35616. * Adds an uniform in the buffer.
  35617. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35618. * for the layout to be correct !
  35619. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35620. * @param {number|number[]} size Data size, or data directly.
  35621. */
  35622. UniformBuffer.prototype.addUniform = function (name, size) {
  35623. if (this._noUBO) {
  35624. return;
  35625. }
  35626. if (this._uniformLocations[name] !== undefined) {
  35627. // Already existing uniform
  35628. return;
  35629. }
  35630. // This function must be called in the order of the shader layout !
  35631. // size can be the size of the uniform, or data directly
  35632. var data;
  35633. if (size instanceof Array) {
  35634. data = size;
  35635. size = data.length;
  35636. }
  35637. else {
  35638. size = size;
  35639. data = [];
  35640. // Fill with zeros
  35641. for (var i = 0; i < size; i++) {
  35642. data.push(0);
  35643. }
  35644. }
  35645. this._fillAlignment(size);
  35646. this._uniformSizes[name] = size;
  35647. this._uniformLocations[name] = this._uniformLocationPointer;
  35648. this._uniformLocationPointer += size;
  35649. for (var i = 0; i < size; i++) {
  35650. this._data.push(data[i]);
  35651. }
  35652. this._needSync = true;
  35653. };
  35654. /**
  35655. * Wrapper for addUniform.
  35656. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35657. * @param {Matrix} mat A 4x4 matrix.
  35658. */
  35659. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35660. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35661. };
  35662. /**
  35663. * Wrapper for addUniform.
  35664. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35665. * @param {number} x
  35666. * @param {number} y
  35667. */
  35668. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35669. var temp = [x, y];
  35670. this.addUniform(name, temp);
  35671. };
  35672. /**
  35673. * Wrapper for addUniform.
  35674. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35675. * @param {number} x
  35676. * @param {number} y
  35677. * @param {number} z
  35678. */
  35679. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35680. var temp = [x, y, z];
  35681. this.addUniform(name, temp);
  35682. };
  35683. /**
  35684. * Wrapper for addUniform.
  35685. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35686. * @param {Color3} color
  35687. */
  35688. UniformBuffer.prototype.addColor3 = function (name, color) {
  35689. var temp = new Array();
  35690. color.toArray(temp);
  35691. this.addUniform(name, temp);
  35692. };
  35693. /**
  35694. * Wrapper for addUniform.
  35695. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35696. * @param {Color3} color
  35697. * @param {number} alpha
  35698. */
  35699. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35700. var temp = new Array();
  35701. color.toArray(temp);
  35702. temp.push(alpha);
  35703. this.addUniform(name, temp);
  35704. };
  35705. /**
  35706. * Wrapper for addUniform.
  35707. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35708. * @param {Vector3} vector
  35709. */
  35710. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35711. var temp = new Array();
  35712. vector.toArray(temp);
  35713. this.addUniform(name, temp);
  35714. };
  35715. /**
  35716. * Wrapper for addUniform.
  35717. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35718. */
  35719. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35720. this.addUniform(name, 12);
  35721. };
  35722. /**
  35723. * Wrapper for addUniform.
  35724. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35725. */
  35726. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35727. this.addUniform(name, 8);
  35728. };
  35729. /**
  35730. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35731. */
  35732. UniformBuffer.prototype.create = function () {
  35733. if (this._noUBO) {
  35734. return;
  35735. }
  35736. if (this._buffer) {
  35737. return; // nothing to do
  35738. }
  35739. // See spec, alignment must be filled as a vec4
  35740. this._fillAlignment(4);
  35741. this._bufferData = new Float32Array(this._data);
  35742. this._rebuild();
  35743. this._needSync = true;
  35744. };
  35745. UniformBuffer.prototype._rebuild = function () {
  35746. if (this._noUBO) {
  35747. return;
  35748. }
  35749. if (this._dynamic) {
  35750. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35751. }
  35752. else {
  35753. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35754. }
  35755. };
  35756. /**
  35757. * Updates the WebGL Uniform Buffer on the GPU.
  35758. * If the `dynamic` flag is set to true, no cache comparison is done.
  35759. * Otherwise, the buffer will be updated only if the cache differs.
  35760. */
  35761. UniformBuffer.prototype.update = function () {
  35762. if (!this._buffer) {
  35763. this.create();
  35764. return;
  35765. }
  35766. if (!this._dynamic && !this._needSync) {
  35767. return;
  35768. }
  35769. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35770. this._needSync = false;
  35771. };
  35772. /**
  35773. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35774. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35775. * @param {number[]|Float32Array} data Flattened data
  35776. * @param {number} size Size of the data.
  35777. */
  35778. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35779. var location = this._uniformLocations[uniformName];
  35780. if (location === undefined) {
  35781. if (this._buffer) {
  35782. // Cannot add an uniform if the buffer is already created
  35783. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35784. return;
  35785. }
  35786. this.addUniform(uniformName, size);
  35787. location = this._uniformLocations[uniformName];
  35788. }
  35789. if (!this._buffer) {
  35790. this.create();
  35791. }
  35792. if (!this._dynamic) {
  35793. // Cache for static uniform buffers
  35794. var changed = false;
  35795. for (var i = 0; i < size; i++) {
  35796. if (this._bufferData[location + i] !== data[i]) {
  35797. changed = true;
  35798. this._bufferData[location + i] = data[i];
  35799. }
  35800. }
  35801. this._needSync = this._needSync || changed;
  35802. }
  35803. else {
  35804. // No cache for dynamic
  35805. for (var i = 0; i < size; i++) {
  35806. this._bufferData[location + i] = data[i];
  35807. }
  35808. }
  35809. };
  35810. // Update methods
  35811. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35812. // To match std140, matrix must be realigned
  35813. for (var i = 0; i < 3; i++) {
  35814. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35815. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35816. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35817. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35818. }
  35819. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35820. };
  35821. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35822. this._currentEffect.setMatrix3x3(name, matrix);
  35823. };
  35824. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35825. this._currentEffect.setMatrix2x2(name, matrix);
  35826. };
  35827. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35828. // To match std140, matrix must be realigned
  35829. for (var i = 0; i < 2; i++) {
  35830. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35831. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35832. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35833. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35834. }
  35835. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35836. };
  35837. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35838. this._currentEffect.setFloat(name, x);
  35839. };
  35840. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35841. UniformBuffer._tempBuffer[0] = x;
  35842. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35843. };
  35844. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35845. if (suffix === void 0) { suffix = ""; }
  35846. this._currentEffect.setFloat2(name + suffix, x, y);
  35847. };
  35848. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35849. if (suffix === void 0) { suffix = ""; }
  35850. UniformBuffer._tempBuffer[0] = x;
  35851. UniformBuffer._tempBuffer[1] = y;
  35852. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35853. };
  35854. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35855. if (suffix === void 0) { suffix = ""; }
  35856. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35857. };
  35858. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35859. if (suffix === void 0) { suffix = ""; }
  35860. UniformBuffer._tempBuffer[0] = x;
  35861. UniformBuffer._tempBuffer[1] = y;
  35862. UniformBuffer._tempBuffer[2] = z;
  35863. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35864. };
  35865. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35866. if (suffix === void 0) { suffix = ""; }
  35867. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35868. };
  35869. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35870. if (suffix === void 0) { suffix = ""; }
  35871. UniformBuffer._tempBuffer[0] = x;
  35872. UniformBuffer._tempBuffer[1] = y;
  35873. UniformBuffer._tempBuffer[2] = z;
  35874. UniformBuffer._tempBuffer[3] = w;
  35875. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35876. };
  35877. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35878. this._currentEffect.setMatrix(name, mat);
  35879. };
  35880. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35881. this.updateUniform(name, mat.toArray(), 16);
  35882. };
  35883. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35884. this._currentEffect.setVector3(name, vector);
  35885. };
  35886. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35887. vector.toArray(UniformBuffer._tempBuffer);
  35888. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35889. };
  35890. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35891. this._currentEffect.setVector4(name, vector);
  35892. };
  35893. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35894. vector.toArray(UniformBuffer._tempBuffer);
  35895. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35896. };
  35897. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35898. if (suffix === void 0) { suffix = ""; }
  35899. this._currentEffect.setColor3(name + suffix, color);
  35900. };
  35901. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35902. if (suffix === void 0) { suffix = ""; }
  35903. color.toArray(UniformBuffer._tempBuffer);
  35904. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35905. };
  35906. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35907. if (suffix === void 0) { suffix = ""; }
  35908. this._currentEffect.setColor4(name + suffix, color, alpha);
  35909. };
  35910. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35911. if (suffix === void 0) { suffix = ""; }
  35912. color.toArray(UniformBuffer._tempBuffer);
  35913. UniformBuffer._tempBuffer[3] = alpha;
  35914. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35915. };
  35916. /**
  35917. * Sets a sampler uniform on the effect.
  35918. * @param {string} name Name of the sampler.
  35919. * @param {Texture} texture
  35920. */
  35921. UniformBuffer.prototype.setTexture = function (name, texture) {
  35922. this._currentEffect.setTexture(name, texture);
  35923. };
  35924. /**
  35925. * Directly updates the value of the uniform in the cache AND on the GPU.
  35926. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35927. * @param {number[]|Float32Array} data Flattened data
  35928. */
  35929. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35930. this.updateUniform(uniformName, data, data.length);
  35931. this.update();
  35932. };
  35933. /**
  35934. * Binds this uniform buffer to an effect.
  35935. * @param {Effect} effect
  35936. * @param {string} name Name of the uniform block in the shader.
  35937. */
  35938. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35939. this._currentEffect = effect;
  35940. if (this._noUBO || !this._buffer) {
  35941. return;
  35942. }
  35943. effect.bindUniformBuffer(this._buffer, name);
  35944. };
  35945. /**
  35946. * Disposes the uniform buffer.
  35947. */
  35948. UniformBuffer.prototype.dispose = function () {
  35949. if (this._noUBO) {
  35950. return;
  35951. }
  35952. var index = this._engine._uniformBuffers.indexOf(this);
  35953. if (index !== -1) {
  35954. this._engine._uniformBuffers.splice(index, 1);
  35955. }
  35956. if (!this._buffer) {
  35957. return;
  35958. }
  35959. if (this._engine._releaseBuffer(this._buffer)) {
  35960. this._buffer = null;
  35961. }
  35962. };
  35963. // Pool for avoiding memory leaks
  35964. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35965. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35966. return UniformBuffer;
  35967. }());
  35968. BABYLON.UniformBuffer = UniformBuffer;
  35969. })(BABYLON || (BABYLON = {}));
  35970. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35971. var BABYLON;
  35972. (function (BABYLON) {
  35973. /**
  35974. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35975. */
  35976. var VertexData = /** @class */ (function () {
  35977. function VertexData() {
  35978. }
  35979. /**
  35980. * Uses the passed data array to set the set the values for the specified kind of data
  35981. * @param data a linear array of floating numbers
  35982. * @param kind the type of data that is being set, eg positions, colors etc
  35983. */
  35984. VertexData.prototype.set = function (data, kind) {
  35985. switch (kind) {
  35986. case BABYLON.VertexBuffer.PositionKind:
  35987. this.positions = data;
  35988. break;
  35989. case BABYLON.VertexBuffer.NormalKind:
  35990. this.normals = data;
  35991. break;
  35992. case BABYLON.VertexBuffer.TangentKind:
  35993. this.tangents = data;
  35994. break;
  35995. case BABYLON.VertexBuffer.UVKind:
  35996. this.uvs = data;
  35997. break;
  35998. case BABYLON.VertexBuffer.UV2Kind:
  35999. this.uvs2 = data;
  36000. break;
  36001. case BABYLON.VertexBuffer.UV3Kind:
  36002. this.uvs3 = data;
  36003. break;
  36004. case BABYLON.VertexBuffer.UV4Kind:
  36005. this.uvs4 = data;
  36006. break;
  36007. case BABYLON.VertexBuffer.UV5Kind:
  36008. this.uvs5 = data;
  36009. break;
  36010. case BABYLON.VertexBuffer.UV6Kind:
  36011. this.uvs6 = data;
  36012. break;
  36013. case BABYLON.VertexBuffer.ColorKind:
  36014. this.colors = data;
  36015. break;
  36016. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36017. this.matricesIndices = data;
  36018. break;
  36019. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36020. this.matricesWeights = data;
  36021. break;
  36022. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36023. this.matricesIndicesExtra = data;
  36024. break;
  36025. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36026. this.matricesWeightsExtra = data;
  36027. break;
  36028. }
  36029. };
  36030. /**
  36031. * Associates the vertexData to the passed Mesh.
  36032. * Sets it as updatable or not (default `false`)
  36033. * @param mesh the mesh the vertexData is applied to
  36034. * @param updatable when used and having the value true allows new data to update the vertexData
  36035. * @returns the VertexData
  36036. */
  36037. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36038. this._applyTo(mesh, updatable);
  36039. return this;
  36040. };
  36041. /**
  36042. * Associates the vertexData to the passed Geometry.
  36043. * Sets it as updatable or not (default `false`)
  36044. * @param geometry the geometry the vertexData is applied to
  36045. * @param updatable when used and having the value true allows new data to update the vertexData
  36046. * @returns VertexData
  36047. */
  36048. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36049. this._applyTo(geometry, updatable);
  36050. return this;
  36051. };
  36052. /**
  36053. * Updates the associated mesh
  36054. * @param mesh the mesh to be updated
  36055. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36056. * @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
  36057. * @returns VertexData
  36058. */
  36059. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36060. this._update(mesh);
  36061. return this;
  36062. };
  36063. /**
  36064. * Updates the associated geometry
  36065. * @param geometry the geometry to be updated
  36066. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36067. * @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
  36068. * @returns VertexData.
  36069. */
  36070. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36071. this._update(geometry);
  36072. return this;
  36073. };
  36074. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36075. if (updatable === void 0) { updatable = false; }
  36076. if (this.positions) {
  36077. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36078. }
  36079. if (this.normals) {
  36080. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36081. }
  36082. if (this.tangents) {
  36083. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36084. }
  36085. if (this.uvs) {
  36086. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36087. }
  36088. if (this.uvs2) {
  36089. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36090. }
  36091. if (this.uvs3) {
  36092. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36093. }
  36094. if (this.uvs4) {
  36095. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36096. }
  36097. if (this.uvs5) {
  36098. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36099. }
  36100. if (this.uvs6) {
  36101. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36102. }
  36103. if (this.colors) {
  36104. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36105. }
  36106. if (this.matricesIndices) {
  36107. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36108. }
  36109. if (this.matricesWeights) {
  36110. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36111. }
  36112. if (this.matricesIndicesExtra) {
  36113. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36114. }
  36115. if (this.matricesWeightsExtra) {
  36116. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36117. }
  36118. if (this.indices) {
  36119. meshOrGeometry.setIndices(this.indices, null, updatable);
  36120. }
  36121. else {
  36122. meshOrGeometry.setIndices([], null);
  36123. }
  36124. return this;
  36125. };
  36126. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36127. if (this.positions) {
  36128. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36129. }
  36130. if (this.normals) {
  36131. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36132. }
  36133. if (this.tangents) {
  36134. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36135. }
  36136. if (this.uvs) {
  36137. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36138. }
  36139. if (this.uvs2) {
  36140. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36141. }
  36142. if (this.uvs3) {
  36143. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36144. }
  36145. if (this.uvs4) {
  36146. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36147. }
  36148. if (this.uvs5) {
  36149. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36150. }
  36151. if (this.uvs6) {
  36152. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36153. }
  36154. if (this.colors) {
  36155. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36156. }
  36157. if (this.matricesIndices) {
  36158. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36159. }
  36160. if (this.matricesWeights) {
  36161. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36162. }
  36163. if (this.matricesIndicesExtra) {
  36164. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36165. }
  36166. if (this.matricesWeightsExtra) {
  36167. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36168. }
  36169. if (this.indices) {
  36170. meshOrGeometry.setIndices(this.indices, null);
  36171. }
  36172. return this;
  36173. };
  36174. /**
  36175. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36176. * @param matrix the transforming matrix
  36177. * @returns the VertexData
  36178. */
  36179. VertexData.prototype.transform = function (matrix) {
  36180. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36181. var transformed = BABYLON.Vector3.Zero();
  36182. var index;
  36183. if (this.positions) {
  36184. var position = BABYLON.Vector3.Zero();
  36185. for (index = 0; index < this.positions.length; index += 3) {
  36186. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36187. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36188. this.positions[index] = transformed.x;
  36189. this.positions[index + 1] = transformed.y;
  36190. this.positions[index + 2] = transformed.z;
  36191. }
  36192. }
  36193. if (this.normals) {
  36194. var normal = BABYLON.Vector3.Zero();
  36195. for (index = 0; index < this.normals.length; index += 3) {
  36196. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36197. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36198. this.normals[index] = transformed.x;
  36199. this.normals[index + 1] = transformed.y;
  36200. this.normals[index + 2] = transformed.z;
  36201. }
  36202. }
  36203. if (this.tangents) {
  36204. var tangent = BABYLON.Vector4.Zero();
  36205. var tangentTransformed = BABYLON.Vector4.Zero();
  36206. for (index = 0; index < this.tangents.length; index += 4) {
  36207. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36208. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36209. this.tangents[index] = tangentTransformed.x;
  36210. this.tangents[index + 1] = tangentTransformed.y;
  36211. this.tangents[index + 2] = tangentTransformed.z;
  36212. this.tangents[index + 3] = tangentTransformed.w;
  36213. }
  36214. }
  36215. if (flip && this.indices) {
  36216. for (index = 0; index < this.indices.length; index += 3) {
  36217. var tmp = this.indices[index + 1];
  36218. this.indices[index + 1] = this.indices[index + 2];
  36219. this.indices[index + 2] = tmp;
  36220. }
  36221. }
  36222. return this;
  36223. };
  36224. /**
  36225. * Merges the passed VertexData into the current one
  36226. * @param other the VertexData to be merged into the current one
  36227. * @returns the modified VertexData
  36228. */
  36229. VertexData.prototype.merge = function (other) {
  36230. this._validate();
  36231. other._validate();
  36232. if (!this.normals !== !other.normals ||
  36233. !this.tangents !== !other.tangents ||
  36234. !this.uvs !== !other.uvs ||
  36235. !this.uvs2 !== !other.uvs2 ||
  36236. !this.uvs3 !== !other.uvs3 ||
  36237. !this.uvs4 !== !other.uvs4 ||
  36238. !this.uvs5 !== !other.uvs5 ||
  36239. !this.uvs6 !== !other.uvs6 ||
  36240. !this.colors !== !other.colors ||
  36241. !this.matricesIndices !== !other.matricesIndices ||
  36242. !this.matricesWeights !== !other.matricesWeights ||
  36243. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36244. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36245. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36246. }
  36247. if (other.indices) {
  36248. if (!this.indices) {
  36249. this.indices = [];
  36250. }
  36251. var offset = this.positions ? this.positions.length / 3 : 0;
  36252. for (var index = 0; index < other.indices.length; index++) {
  36253. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36254. this.indices.push(other.indices[index] + offset);
  36255. }
  36256. }
  36257. this.positions = this._mergeElement(this.positions, other.positions);
  36258. this.normals = this._mergeElement(this.normals, other.normals);
  36259. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36260. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36261. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36262. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36263. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36264. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36265. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36266. this.colors = this._mergeElement(this.colors, other.colors);
  36267. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36268. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36269. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36270. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36271. return this;
  36272. };
  36273. VertexData.prototype._mergeElement = function (source, other) {
  36274. if (!source) {
  36275. return other;
  36276. }
  36277. if (!other) {
  36278. return source;
  36279. }
  36280. var len = other.length + source.length;
  36281. var isSrcTypedArray = source instanceof Float32Array;
  36282. var isOthTypedArray = other instanceof Float32Array;
  36283. // use non-loop method when the source is Float32Array
  36284. if (isSrcTypedArray) {
  36285. var ret32 = new Float32Array(len);
  36286. ret32.set(source);
  36287. ret32.set(other, source.length);
  36288. return ret32;
  36289. // source is number[], when other is also use concat
  36290. }
  36291. else if (!isOthTypedArray) {
  36292. return source.concat(other);
  36293. // source is a number[], but other is a Float32Array, loop required
  36294. }
  36295. else {
  36296. var ret = source.slice(0); // copy source to a separate array
  36297. for (var i = 0, len = other.length; i < len; i++) {
  36298. ret.push(other[i]);
  36299. }
  36300. return ret;
  36301. }
  36302. };
  36303. VertexData.prototype._validate = function () {
  36304. if (!this.positions) {
  36305. throw new Error("Positions are required");
  36306. }
  36307. var getElementCount = function (kind, values) {
  36308. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36309. if ((values.length % stride) !== 0) {
  36310. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36311. }
  36312. return values.length / stride;
  36313. };
  36314. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36315. var validateElementCount = function (kind, values) {
  36316. var elementCount = getElementCount(kind, values);
  36317. if (elementCount !== positionsElementCount) {
  36318. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36319. }
  36320. };
  36321. if (this.normals)
  36322. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36323. if (this.tangents)
  36324. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36325. if (this.uvs)
  36326. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36327. if (this.uvs2)
  36328. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36329. if (this.uvs3)
  36330. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36331. if (this.uvs4)
  36332. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36333. if (this.uvs5)
  36334. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36335. if (this.uvs6)
  36336. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36337. if (this.colors)
  36338. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36339. if (this.matricesIndices)
  36340. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36341. if (this.matricesWeights)
  36342. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36343. if (this.matricesIndicesExtra)
  36344. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36345. if (this.matricesWeightsExtra)
  36346. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36347. };
  36348. /**
  36349. * Serializes the VertexData
  36350. * @returns a serialized object
  36351. */
  36352. VertexData.prototype.serialize = function () {
  36353. var serializationObject = this.serialize();
  36354. if (this.positions) {
  36355. serializationObject.positions = this.positions;
  36356. }
  36357. if (this.normals) {
  36358. serializationObject.normals = this.normals;
  36359. }
  36360. if (this.tangents) {
  36361. serializationObject.tangents = this.tangents;
  36362. }
  36363. if (this.uvs) {
  36364. serializationObject.uvs = this.uvs;
  36365. }
  36366. if (this.uvs2) {
  36367. serializationObject.uvs2 = this.uvs2;
  36368. }
  36369. if (this.uvs3) {
  36370. serializationObject.uvs3 = this.uvs3;
  36371. }
  36372. if (this.uvs4) {
  36373. serializationObject.uvs4 = this.uvs4;
  36374. }
  36375. if (this.uvs5) {
  36376. serializationObject.uvs5 = this.uvs5;
  36377. }
  36378. if (this.uvs6) {
  36379. serializationObject.uvs6 = this.uvs6;
  36380. }
  36381. if (this.colors) {
  36382. serializationObject.colors = this.colors;
  36383. }
  36384. if (this.matricesIndices) {
  36385. serializationObject.matricesIndices = this.matricesIndices;
  36386. serializationObject.matricesIndices._isExpanded = true;
  36387. }
  36388. if (this.matricesWeights) {
  36389. serializationObject.matricesWeights = this.matricesWeights;
  36390. }
  36391. if (this.matricesIndicesExtra) {
  36392. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36393. serializationObject.matricesIndicesExtra._isExpanded = true;
  36394. }
  36395. if (this.matricesWeightsExtra) {
  36396. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36397. }
  36398. serializationObject.indices = this.indices;
  36399. return serializationObject;
  36400. };
  36401. // Statics
  36402. /**
  36403. * Extracts the vertexData from a mesh
  36404. * @param mesh the mesh from which to extract the VertexData
  36405. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36406. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36407. * @returns the object VertexData associated to the passed mesh
  36408. */
  36409. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36410. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36411. };
  36412. /**
  36413. * Extracts the vertexData from the geometry
  36414. * @param geometry the geometry from which to extract the VertexData
  36415. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36416. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36417. * @returns the object VertexData associated to the passed mesh
  36418. */
  36419. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36420. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36421. };
  36422. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36423. var result = new VertexData();
  36424. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36425. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36426. }
  36427. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36428. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36429. }
  36430. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36431. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36432. }
  36433. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36434. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36435. }
  36436. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36437. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36438. }
  36439. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36440. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36441. }
  36442. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36443. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36444. }
  36445. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36446. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36447. }
  36448. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36449. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36450. }
  36451. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36452. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36453. }
  36454. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36455. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36456. }
  36457. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36458. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36459. }
  36460. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36461. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36462. }
  36463. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36464. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36465. }
  36466. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36467. return result;
  36468. };
  36469. /**
  36470. * Creates the VertexData for a Ribbon
  36471. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36472. * * pathArray array of paths, each of which an array of successive Vector3
  36473. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36474. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36475. * * 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
  36476. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36477. * * 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)
  36478. * * 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)
  36479. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36480. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36481. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36482. * @returns the VertexData of the ribbon
  36483. */
  36484. VertexData.CreateRibbon = function (options) {
  36485. var pathArray = options.pathArray;
  36486. var closeArray = options.closeArray || false;
  36487. var closePath = options.closePath || false;
  36488. var invertUV = options.invertUV || false;
  36489. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36490. var offset = options.offset || defaultOffset;
  36491. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36492. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36493. var customUV = options.uvs;
  36494. var customColors = options.colors;
  36495. var positions = [];
  36496. var indices = [];
  36497. var normals = [];
  36498. var uvs = [];
  36499. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36500. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36501. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36502. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36503. var minlg; // minimal length among all paths from pathArray
  36504. var lg = []; // array of path lengths : nb of vertex per path
  36505. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36506. var p; // path iterator
  36507. var i; // point iterator
  36508. var j; // point iterator
  36509. // if single path in pathArray
  36510. if (pathArray.length < 2) {
  36511. var ar1 = [];
  36512. var ar2 = [];
  36513. for (i = 0; i < pathArray[0].length - offset; i++) {
  36514. ar1.push(pathArray[0][i]);
  36515. ar2.push(pathArray[0][i + offset]);
  36516. }
  36517. pathArray = [ar1, ar2];
  36518. }
  36519. // positions and horizontal distances (u)
  36520. var idc = 0;
  36521. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36522. var path;
  36523. var l;
  36524. minlg = pathArray[0].length;
  36525. var vectlg;
  36526. var dist;
  36527. for (p = 0; p < pathArray.length; p++) {
  36528. uTotalDistance[p] = 0;
  36529. us[p] = [0];
  36530. path = pathArray[p];
  36531. l = path.length;
  36532. minlg = (minlg < l) ? minlg : l;
  36533. j = 0;
  36534. while (j < l) {
  36535. positions.push(path[j].x, path[j].y, path[j].z);
  36536. if (j > 0) {
  36537. vectlg = path[j].subtract(path[j - 1]).length();
  36538. dist = vectlg + uTotalDistance[p];
  36539. us[p].push(dist);
  36540. uTotalDistance[p] = dist;
  36541. }
  36542. j++;
  36543. }
  36544. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36545. j--;
  36546. positions.push(path[0].x, path[0].y, path[0].z);
  36547. vectlg = path[j].subtract(path[0]).length();
  36548. dist = vectlg + uTotalDistance[p];
  36549. us[p].push(dist);
  36550. uTotalDistance[p] = dist;
  36551. }
  36552. lg[p] = l + closePathCorr;
  36553. idx[p] = idc;
  36554. idc += (l + closePathCorr);
  36555. }
  36556. // vertical distances (v)
  36557. var path1;
  36558. var path2;
  36559. var vertex1 = null;
  36560. var vertex2 = null;
  36561. for (i = 0; i < minlg + closePathCorr; i++) {
  36562. vTotalDistance[i] = 0;
  36563. vs[i] = [0];
  36564. for (p = 0; p < pathArray.length - 1; p++) {
  36565. path1 = pathArray[p];
  36566. path2 = pathArray[p + 1];
  36567. if (i === minlg) { // closePath
  36568. vertex1 = path1[0];
  36569. vertex2 = path2[0];
  36570. }
  36571. else {
  36572. vertex1 = path1[i];
  36573. vertex2 = path2[i];
  36574. }
  36575. vectlg = vertex2.subtract(vertex1).length();
  36576. dist = vectlg + vTotalDistance[i];
  36577. vs[i].push(dist);
  36578. vTotalDistance[i] = dist;
  36579. }
  36580. if (closeArray && vertex2 && vertex1) {
  36581. path1 = pathArray[p];
  36582. path2 = pathArray[0];
  36583. if (i === minlg) { // closePath
  36584. vertex2 = path2[0];
  36585. }
  36586. vectlg = vertex2.subtract(vertex1).length();
  36587. dist = vectlg + vTotalDistance[i];
  36588. vTotalDistance[i] = dist;
  36589. }
  36590. }
  36591. // uvs
  36592. var u;
  36593. var v;
  36594. if (customUV) {
  36595. for (p = 0; p < customUV.length; p++) {
  36596. uvs.push(customUV[p].x, customUV[p].y);
  36597. }
  36598. }
  36599. else {
  36600. for (p = 0; p < pathArray.length; p++) {
  36601. for (i = 0; i < minlg + closePathCorr; i++) {
  36602. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36603. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36604. if (invertUV) {
  36605. uvs.push(v, u);
  36606. }
  36607. else {
  36608. uvs.push(u, v);
  36609. }
  36610. }
  36611. }
  36612. }
  36613. // indices
  36614. p = 0; // path index
  36615. var pi = 0; // positions array index
  36616. var l1 = lg[p] - 1; // path1 length
  36617. var l2 = lg[p + 1] - 1; // path2 length
  36618. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36619. var shft = idx[1] - idx[0]; // shift
  36620. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36621. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36622. // 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
  36623. indices.push(pi, pi + shft, pi + 1);
  36624. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36625. pi += 1;
  36626. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36627. p++;
  36628. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36629. shft = idx[0] - idx[p];
  36630. l1 = lg[p] - 1;
  36631. l2 = lg[0] - 1;
  36632. }
  36633. else {
  36634. shft = idx[p + 1] - idx[p];
  36635. l1 = lg[p] - 1;
  36636. l2 = lg[p + 1] - 1;
  36637. }
  36638. pi = idx[p];
  36639. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36640. }
  36641. }
  36642. // normals
  36643. VertexData.ComputeNormals(positions, indices, normals);
  36644. if (closePath) { // update both the first and last vertex normals to their average value
  36645. var indexFirst = 0;
  36646. var indexLast = 0;
  36647. for (p = 0; p < pathArray.length; p++) {
  36648. indexFirst = idx[p] * 3;
  36649. if (p + 1 < pathArray.length) {
  36650. indexLast = (idx[p + 1] - 1) * 3;
  36651. }
  36652. else {
  36653. indexLast = normals.length - 3;
  36654. }
  36655. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36656. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36657. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36658. normals[indexLast] = normals[indexFirst];
  36659. normals[indexLast + 1] = normals[indexFirst + 1];
  36660. normals[indexLast + 2] = normals[indexFirst + 2];
  36661. }
  36662. }
  36663. // sides
  36664. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36665. // Colors
  36666. var colors = null;
  36667. if (customColors) {
  36668. colors = new Float32Array(customColors.length * 4);
  36669. for (var c = 0; c < customColors.length; c++) {
  36670. colors[c * 4] = customColors[c].r;
  36671. colors[c * 4 + 1] = customColors[c].g;
  36672. colors[c * 4 + 2] = customColors[c].b;
  36673. colors[c * 4 + 3] = customColors[c].a;
  36674. }
  36675. }
  36676. // Result
  36677. var vertexData = new VertexData();
  36678. var positions32 = new Float32Array(positions);
  36679. var normals32 = new Float32Array(normals);
  36680. var uvs32 = new Float32Array(uvs);
  36681. vertexData.indices = indices;
  36682. vertexData.positions = positions32;
  36683. vertexData.normals = normals32;
  36684. vertexData.uvs = uvs32;
  36685. if (colors) {
  36686. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36687. }
  36688. if (closePath) {
  36689. vertexData._idx = idx;
  36690. }
  36691. return vertexData;
  36692. };
  36693. /**
  36694. * Creates the VertexData for a box
  36695. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36696. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36697. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36698. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36699. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36700. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36701. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36702. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36703. * * 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)
  36704. * * 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)
  36705. * @returns the VertexData of the box
  36706. */
  36707. VertexData.CreateBox = function (options) {
  36708. var normalsSource = [
  36709. new BABYLON.Vector3(0, 0, 1),
  36710. new BABYLON.Vector3(0, 0, -1),
  36711. new BABYLON.Vector3(1, 0, 0),
  36712. new BABYLON.Vector3(-1, 0, 0),
  36713. new BABYLON.Vector3(0, 1, 0),
  36714. new BABYLON.Vector3(0, -1, 0)
  36715. ];
  36716. var indices = [];
  36717. var positions = [];
  36718. var normals = [];
  36719. var uvs = [];
  36720. var width = options.width || options.size || 1;
  36721. var height = options.height || options.size || 1;
  36722. var depth = options.depth || options.size || 1;
  36723. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36724. var faceUV = options.faceUV || new Array(6);
  36725. var faceColors = options.faceColors;
  36726. var colors = [];
  36727. // default face colors and UV if undefined
  36728. for (var f = 0; f < 6; f++) {
  36729. if (faceUV[f] === undefined) {
  36730. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36731. }
  36732. if (faceColors && faceColors[f] === undefined) {
  36733. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36734. }
  36735. }
  36736. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36737. // Create each face in turn.
  36738. for (var index = 0; index < normalsSource.length; index++) {
  36739. var normal = normalsSource[index];
  36740. // Get two vectors perpendicular to the face normal and to each other.
  36741. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36742. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36743. // Six indices (two triangles) per face.
  36744. var verticesLength = positions.length / 3;
  36745. indices.push(verticesLength);
  36746. indices.push(verticesLength + 1);
  36747. indices.push(verticesLength + 2);
  36748. indices.push(verticesLength);
  36749. indices.push(verticesLength + 2);
  36750. indices.push(verticesLength + 3);
  36751. // Four vertices per face.
  36752. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36753. positions.push(vertex.x, vertex.y, vertex.z);
  36754. normals.push(normal.x, normal.y, normal.z);
  36755. uvs.push(faceUV[index].z, faceUV[index].w);
  36756. if (faceColors) {
  36757. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36758. }
  36759. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36760. positions.push(vertex.x, vertex.y, vertex.z);
  36761. normals.push(normal.x, normal.y, normal.z);
  36762. uvs.push(faceUV[index].x, faceUV[index].w);
  36763. if (faceColors) {
  36764. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36765. }
  36766. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36767. positions.push(vertex.x, vertex.y, vertex.z);
  36768. normals.push(normal.x, normal.y, normal.z);
  36769. uvs.push(faceUV[index].x, faceUV[index].y);
  36770. if (faceColors) {
  36771. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36772. }
  36773. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36774. positions.push(vertex.x, vertex.y, vertex.z);
  36775. normals.push(normal.x, normal.y, normal.z);
  36776. uvs.push(faceUV[index].z, faceUV[index].y);
  36777. if (faceColors) {
  36778. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36779. }
  36780. }
  36781. // sides
  36782. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36783. // Result
  36784. var vertexData = new VertexData();
  36785. vertexData.indices = indices;
  36786. vertexData.positions = positions;
  36787. vertexData.normals = normals;
  36788. vertexData.uvs = uvs;
  36789. if (faceColors) {
  36790. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36791. vertexData.colors = totalColors;
  36792. }
  36793. return vertexData;
  36794. };
  36795. /**
  36796. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36797. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36798. * * segments sets the number of horizontal strips optional, default 32
  36799. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36800. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36801. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36802. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36803. * * 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
  36804. * * 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
  36805. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36806. * * 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)
  36807. * * 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)
  36808. * @returns the VertexData of the ellipsoid
  36809. */
  36810. VertexData.CreateSphere = function (options) {
  36811. var segments = options.segments || 32;
  36812. var diameterX = options.diameterX || options.diameter || 1;
  36813. var diameterY = options.diameterY || options.diameter || 1;
  36814. var diameterZ = options.diameterZ || options.diameter || 1;
  36815. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36816. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36817. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36818. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36819. var totalZRotationSteps = 2 + segments;
  36820. var totalYRotationSteps = 2 * totalZRotationSteps;
  36821. var indices = [];
  36822. var positions = [];
  36823. var normals = [];
  36824. var uvs = [];
  36825. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36826. var normalizedZ = zRotationStep / totalZRotationSteps;
  36827. var angleZ = normalizedZ * Math.PI * slice;
  36828. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36829. var normalizedY = yRotationStep / totalYRotationSteps;
  36830. var angleY = normalizedY * Math.PI * 2 * arc;
  36831. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36832. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36833. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36834. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36835. var vertex = complete.multiply(radius);
  36836. var normal = complete.divide(radius).normalize();
  36837. positions.push(vertex.x, vertex.y, vertex.z);
  36838. normals.push(normal.x, normal.y, normal.z);
  36839. uvs.push(normalizedY, normalizedZ);
  36840. }
  36841. if (zRotationStep > 0) {
  36842. var verticesCount = positions.length / 3;
  36843. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36844. indices.push((firstIndex));
  36845. indices.push((firstIndex + 1));
  36846. indices.push(firstIndex + totalYRotationSteps + 1);
  36847. indices.push((firstIndex + totalYRotationSteps + 1));
  36848. indices.push((firstIndex + 1));
  36849. indices.push((firstIndex + totalYRotationSteps + 2));
  36850. }
  36851. }
  36852. }
  36853. // Sides
  36854. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36855. // Result
  36856. var vertexData = new VertexData();
  36857. vertexData.indices = indices;
  36858. vertexData.positions = positions;
  36859. vertexData.normals = normals;
  36860. vertexData.uvs = uvs;
  36861. return vertexData;
  36862. };
  36863. /**
  36864. * Creates the VertexData for a cylinder, cone or prism
  36865. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36866. * * height sets the height (y direction) of the cylinder, optional, default 2
  36867. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36868. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36869. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36870. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36871. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36872. * * 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
  36873. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36874. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36875. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36876. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36877. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36878. * * 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)
  36879. * * 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)
  36880. * @returns the VertexData of the cylinder, cone or prism
  36881. */
  36882. VertexData.CreateCylinder = function (options) {
  36883. var height = options.height || 2;
  36884. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36885. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36886. var tessellation = options.tessellation || 24;
  36887. var subdivisions = options.subdivisions || 1;
  36888. var hasRings = options.hasRings ? true : false;
  36889. var enclose = options.enclose ? true : false;
  36890. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36891. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36892. var faceUV = options.faceUV || new Array(3);
  36893. var faceColors = options.faceColors;
  36894. // default face colors and UV if undefined
  36895. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36896. var ringNb = (hasRings) ? subdivisions : 1;
  36897. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36898. var f;
  36899. for (f = 0; f < surfaceNb; f++) {
  36900. if (faceColors && faceColors[f] === undefined) {
  36901. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36902. }
  36903. }
  36904. for (f = 0; f < surfaceNb; f++) {
  36905. if (faceUV && faceUV[f] === undefined) {
  36906. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36907. }
  36908. }
  36909. var indices = new Array();
  36910. var positions = new Array();
  36911. var normals = new Array();
  36912. var uvs = new Array();
  36913. var colors = new Array();
  36914. var angle_step = Math.PI * 2 * arc / tessellation;
  36915. var angle;
  36916. var h;
  36917. var radius;
  36918. var tan = (diameterBottom - diameterTop) / 2 / height;
  36919. var ringVertex = BABYLON.Vector3.Zero();
  36920. var ringNormal = BABYLON.Vector3.Zero();
  36921. var ringFirstVertex = BABYLON.Vector3.Zero();
  36922. var ringFirstNormal = BABYLON.Vector3.Zero();
  36923. var quadNormal = BABYLON.Vector3.Zero();
  36924. var Y = BABYLON.Axis.Y;
  36925. // positions, normals, uvs
  36926. var i;
  36927. var j;
  36928. var r;
  36929. var ringIdx = 1;
  36930. var s = 1; // surface index
  36931. var cs = 0;
  36932. var v = 0;
  36933. for (i = 0; i <= subdivisions; i++) {
  36934. h = i / subdivisions;
  36935. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36936. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36937. for (r = 0; r < ringIdx; r++) {
  36938. if (hasRings) {
  36939. s += r;
  36940. }
  36941. if (enclose) {
  36942. s += 2 * r;
  36943. }
  36944. for (j = 0; j <= tessellation; j++) {
  36945. angle = j * angle_step;
  36946. // position
  36947. ringVertex.x = Math.cos(-angle) * radius;
  36948. ringVertex.y = -height / 2 + h * height;
  36949. ringVertex.z = Math.sin(-angle) * radius;
  36950. // normal
  36951. if (diameterTop === 0 && i === subdivisions) {
  36952. // if no top cap, reuse former normals
  36953. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36954. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36955. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36956. }
  36957. else {
  36958. ringNormal.x = ringVertex.x;
  36959. ringNormal.z = ringVertex.z;
  36960. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36961. ringNormal.normalize();
  36962. }
  36963. // keep first ring vertex values for enclose
  36964. if (j === 0) {
  36965. ringFirstVertex.copyFrom(ringVertex);
  36966. ringFirstNormal.copyFrom(ringNormal);
  36967. }
  36968. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36969. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36970. if (hasRings) {
  36971. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36972. }
  36973. else {
  36974. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36975. }
  36976. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36977. if (faceColors) {
  36978. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36979. }
  36980. }
  36981. // if enclose, add four vertices and their dedicated normals
  36982. if (arc !== 1 && enclose) {
  36983. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36984. positions.push(0, ringVertex.y, 0);
  36985. positions.push(0, ringVertex.y, 0);
  36986. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36987. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36988. quadNormal.normalize();
  36989. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36990. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36991. quadNormal.normalize();
  36992. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36993. if (hasRings) {
  36994. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36995. }
  36996. else {
  36997. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36998. }
  36999. uvs.push(faceUV[s + 1].x, v);
  37000. uvs.push(faceUV[s + 1].z, v);
  37001. if (hasRings) {
  37002. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37003. }
  37004. else {
  37005. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37006. }
  37007. uvs.push(faceUV[s + 2].x, v);
  37008. uvs.push(faceUV[s + 2].z, v);
  37009. if (faceColors) {
  37010. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37011. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37012. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37013. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37014. }
  37015. }
  37016. if (cs !== s) {
  37017. cs = s;
  37018. }
  37019. }
  37020. }
  37021. // indices
  37022. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37023. var s;
  37024. i = 0;
  37025. for (s = 0; s < subdivisions; s++) {
  37026. var i0 = 0;
  37027. var i1 = 0;
  37028. var i2 = 0;
  37029. var i3 = 0;
  37030. for (j = 0; j < tessellation; j++) {
  37031. i0 = i * (e + 1) + j;
  37032. i1 = (i + 1) * (e + 1) + j;
  37033. i2 = i * (e + 1) + (j + 1);
  37034. i3 = (i + 1) * (e + 1) + (j + 1);
  37035. indices.push(i0, i1, i2);
  37036. indices.push(i3, i2, i1);
  37037. }
  37038. if (arc !== 1 && enclose) { // if enclose, add two quads
  37039. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37040. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37041. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37042. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37043. }
  37044. i = (hasRings) ? (i + 2) : (i + 1);
  37045. }
  37046. // Caps
  37047. var createCylinderCap = function (isTop) {
  37048. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37049. if (radius === 0) {
  37050. return;
  37051. }
  37052. // Cap positions, normals & uvs
  37053. var angle;
  37054. var circleVector;
  37055. var i;
  37056. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37057. var c = null;
  37058. if (faceColors) {
  37059. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37060. }
  37061. // cap center
  37062. var vbase = positions.length / 3;
  37063. var offset = isTop ? height / 2 : -height / 2;
  37064. var center = new BABYLON.Vector3(0, offset, 0);
  37065. positions.push(center.x, center.y, center.z);
  37066. normals.push(0, isTop ? 1 : -1, 0);
  37067. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37068. if (c) {
  37069. colors.push(c.r, c.g, c.b, c.a);
  37070. }
  37071. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37072. for (i = 0; i <= tessellation; i++) {
  37073. angle = Math.PI * 2 * i * arc / tessellation;
  37074. var cos = Math.cos(-angle);
  37075. var sin = Math.sin(-angle);
  37076. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37077. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37078. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37079. normals.push(0, isTop ? 1 : -1, 0);
  37080. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37081. if (c) {
  37082. colors.push(c.r, c.g, c.b, c.a);
  37083. }
  37084. }
  37085. // Cap indices
  37086. for (i = 0; i < tessellation; i++) {
  37087. if (!isTop) {
  37088. indices.push(vbase);
  37089. indices.push(vbase + (i + 1));
  37090. indices.push(vbase + (i + 2));
  37091. }
  37092. else {
  37093. indices.push(vbase);
  37094. indices.push(vbase + (i + 2));
  37095. indices.push(vbase + (i + 1));
  37096. }
  37097. }
  37098. };
  37099. // add caps to geometry
  37100. createCylinderCap(false);
  37101. createCylinderCap(true);
  37102. // Sides
  37103. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37104. var vertexData = new VertexData();
  37105. vertexData.indices = indices;
  37106. vertexData.positions = positions;
  37107. vertexData.normals = normals;
  37108. vertexData.uvs = uvs;
  37109. if (faceColors) {
  37110. vertexData.colors = colors;
  37111. }
  37112. return vertexData;
  37113. };
  37114. /**
  37115. * Creates the VertexData for a torus
  37116. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37117. * * diameter the diameter of the torus, optional default 1
  37118. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37119. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37120. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37121. * * 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)
  37122. * * 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)
  37123. * @returns the VertexData of the torus
  37124. */
  37125. VertexData.CreateTorus = function (options) {
  37126. var indices = [];
  37127. var positions = [];
  37128. var normals = [];
  37129. var uvs = [];
  37130. var diameter = options.diameter || 1;
  37131. var thickness = options.thickness || 0.5;
  37132. var tessellation = options.tessellation || 16;
  37133. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37134. var stride = tessellation + 1;
  37135. for (var i = 0; i <= tessellation; i++) {
  37136. var u = i / tessellation;
  37137. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37138. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37139. for (var j = 0; j <= tessellation; j++) {
  37140. var v = 1 - j / tessellation;
  37141. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37142. var dx = Math.cos(innerAngle);
  37143. var dy = Math.sin(innerAngle);
  37144. // Create a vertex.
  37145. var normal = new BABYLON.Vector3(dx, dy, 0);
  37146. var position = normal.scale(thickness / 2);
  37147. var textureCoordinate = new BABYLON.Vector2(u, v);
  37148. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37149. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37150. positions.push(position.x, position.y, position.z);
  37151. normals.push(normal.x, normal.y, normal.z);
  37152. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37153. // And create indices for two triangles.
  37154. var nextI = (i + 1) % stride;
  37155. var nextJ = (j + 1) % stride;
  37156. indices.push(i * stride + j);
  37157. indices.push(i * stride + nextJ);
  37158. indices.push(nextI * stride + j);
  37159. indices.push(i * stride + nextJ);
  37160. indices.push(nextI * stride + nextJ);
  37161. indices.push(nextI * stride + j);
  37162. }
  37163. }
  37164. // Sides
  37165. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37166. // Result
  37167. var vertexData = new VertexData();
  37168. vertexData.indices = indices;
  37169. vertexData.positions = positions;
  37170. vertexData.normals = normals;
  37171. vertexData.uvs = uvs;
  37172. return vertexData;
  37173. };
  37174. /**
  37175. * Creates the VertexData of the LineSystem
  37176. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37177. * - lines an array of lines, each line being an array of successive Vector3
  37178. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37179. * @returns the VertexData of the LineSystem
  37180. */
  37181. VertexData.CreateLineSystem = function (options) {
  37182. var indices = [];
  37183. var positions = [];
  37184. var lines = options.lines;
  37185. var colors = options.colors;
  37186. var vertexColors = [];
  37187. var idx = 0;
  37188. for (var l = 0; l < lines.length; l++) {
  37189. var points = lines[l];
  37190. for (var index = 0; index < points.length; index++) {
  37191. positions.push(points[index].x, points[index].y, points[index].z);
  37192. if (colors) {
  37193. var color = colors[l];
  37194. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37195. }
  37196. if (index > 0) {
  37197. indices.push(idx - 1);
  37198. indices.push(idx);
  37199. }
  37200. idx++;
  37201. }
  37202. }
  37203. var vertexData = new VertexData();
  37204. vertexData.indices = indices;
  37205. vertexData.positions = positions;
  37206. if (colors) {
  37207. vertexData.colors = vertexColors;
  37208. }
  37209. return vertexData;
  37210. };
  37211. /**
  37212. * Create the VertexData for a DashedLines
  37213. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37214. * - points an array successive Vector3
  37215. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37216. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37217. * - dashNb the intended total number of dashes, optional, default 200
  37218. * @returns the VertexData for the DashedLines
  37219. */
  37220. VertexData.CreateDashedLines = function (options) {
  37221. var dashSize = options.dashSize || 3;
  37222. var gapSize = options.gapSize || 1;
  37223. var dashNb = options.dashNb || 200;
  37224. var points = options.points;
  37225. var positions = new Array();
  37226. var indices = new Array();
  37227. var curvect = BABYLON.Vector3.Zero();
  37228. var lg = 0;
  37229. var nb = 0;
  37230. var shft = 0;
  37231. var dashshft = 0;
  37232. var curshft = 0;
  37233. var idx = 0;
  37234. var i = 0;
  37235. for (i = 0; i < points.length - 1; i++) {
  37236. points[i + 1].subtractToRef(points[i], curvect);
  37237. lg += curvect.length();
  37238. }
  37239. shft = lg / dashNb;
  37240. dashshft = dashSize * shft / (dashSize + gapSize);
  37241. for (i = 0; i < points.length - 1; i++) {
  37242. points[i + 1].subtractToRef(points[i], curvect);
  37243. nb = Math.floor(curvect.length() / shft);
  37244. curvect.normalize();
  37245. for (var j = 0; j < nb; j++) {
  37246. curshft = shft * j;
  37247. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37248. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37249. indices.push(idx, idx + 1);
  37250. idx += 2;
  37251. }
  37252. }
  37253. // Result
  37254. var vertexData = new VertexData();
  37255. vertexData.positions = positions;
  37256. vertexData.indices = indices;
  37257. return vertexData;
  37258. };
  37259. /**
  37260. * Creates the VertexData for a Ground
  37261. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37262. * - width the width (x direction) of the ground, optional, default 1
  37263. * - height the height (z direction) of the ground, optional, default 1
  37264. * - subdivisions the number of subdivisions per side, optional, default 1
  37265. * @returns the VertexData of the Ground
  37266. */
  37267. VertexData.CreateGround = function (options) {
  37268. var indices = [];
  37269. var positions = [];
  37270. var normals = [];
  37271. var uvs = [];
  37272. var row, col;
  37273. var width = options.width || 1;
  37274. var height = options.height || 1;
  37275. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37276. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37277. for (row = 0; row <= subdivisionsY; row++) {
  37278. for (col = 0; col <= subdivisionsX; col++) {
  37279. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37280. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37281. positions.push(position.x, position.y, position.z);
  37282. normals.push(normal.x, normal.y, normal.z);
  37283. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37284. }
  37285. }
  37286. for (row = 0; row < subdivisionsY; row++) {
  37287. for (col = 0; col < subdivisionsX; col++) {
  37288. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37289. indices.push(col + 1 + row * (subdivisionsX + 1));
  37290. indices.push(col + row * (subdivisionsX + 1));
  37291. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37292. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37293. indices.push(col + row * (subdivisionsX + 1));
  37294. }
  37295. }
  37296. // Result
  37297. var vertexData = new VertexData();
  37298. vertexData.indices = indices;
  37299. vertexData.positions = positions;
  37300. vertexData.normals = normals;
  37301. vertexData.uvs = uvs;
  37302. return vertexData;
  37303. };
  37304. /**
  37305. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37306. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37307. * * xmin the ground minimum X coordinate, optional, default -1
  37308. * * zmin the ground minimum Z coordinate, optional, default -1
  37309. * * xmax the ground maximum X coordinate, optional, default 1
  37310. * * zmax the ground maximum Z coordinate, optional, default 1
  37311. * * 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}
  37312. * * 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}
  37313. * @returns the VertexData of the TiledGround
  37314. */
  37315. VertexData.CreateTiledGround = function (options) {
  37316. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37317. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37318. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37319. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37320. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37321. var precision = options.precision || { w: 1, h: 1 };
  37322. var indices = new Array();
  37323. var positions = new Array();
  37324. var normals = new Array();
  37325. var uvs = new Array();
  37326. var row, col, tileRow, tileCol;
  37327. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37328. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37329. precision.w = (precision.w < 1) ? 1 : precision.w;
  37330. precision.h = (precision.h < 1) ? 1 : precision.h;
  37331. var tileSize = {
  37332. 'w': (xmax - xmin) / subdivisions.w,
  37333. 'h': (zmax - zmin) / subdivisions.h
  37334. };
  37335. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37336. // Indices
  37337. var base = positions.length / 3;
  37338. var rowLength = precision.w + 1;
  37339. for (row = 0; row < precision.h; row++) {
  37340. for (col = 0; col < precision.w; col++) {
  37341. var square = [
  37342. base + col + row * rowLength,
  37343. base + (col + 1) + row * rowLength,
  37344. base + (col + 1) + (row + 1) * rowLength,
  37345. base + col + (row + 1) * rowLength
  37346. ];
  37347. indices.push(square[1]);
  37348. indices.push(square[2]);
  37349. indices.push(square[3]);
  37350. indices.push(square[0]);
  37351. indices.push(square[1]);
  37352. indices.push(square[3]);
  37353. }
  37354. }
  37355. // Position, normals and uvs
  37356. var position = BABYLON.Vector3.Zero();
  37357. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37358. for (row = 0; row <= precision.h; row++) {
  37359. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37360. for (col = 0; col <= precision.w; col++) {
  37361. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37362. position.y = 0;
  37363. positions.push(position.x, position.y, position.z);
  37364. normals.push(normal.x, normal.y, normal.z);
  37365. uvs.push(col / precision.w, row / precision.h);
  37366. }
  37367. }
  37368. }
  37369. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37370. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37371. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37372. }
  37373. }
  37374. // Result
  37375. var vertexData = new VertexData();
  37376. vertexData.indices = indices;
  37377. vertexData.positions = positions;
  37378. vertexData.normals = normals;
  37379. vertexData.uvs = uvs;
  37380. return vertexData;
  37381. };
  37382. /**
  37383. * Creates the VertexData of the Ground designed from a heightmap
  37384. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37385. * * width the width (x direction) of the ground
  37386. * * height the height (z direction) of the ground
  37387. * * subdivisions the number of subdivisions per side
  37388. * * minHeight the minimum altitude on the ground, optional, default 0
  37389. * * maxHeight the maximum altitude on the ground, optional default 1
  37390. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37391. * * buffer the array holding the image color data
  37392. * * bufferWidth the width of image
  37393. * * bufferHeight the height of image
  37394. * @returns the VertexData of the Ground designed from a heightmap
  37395. */
  37396. VertexData.CreateGroundFromHeightMap = function (options) {
  37397. var indices = [];
  37398. var positions = [];
  37399. var normals = [];
  37400. var uvs = [];
  37401. var row, col;
  37402. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37403. // Vertices
  37404. for (row = 0; row <= options.subdivisions; row++) {
  37405. for (col = 0; col <= options.subdivisions; col++) {
  37406. 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));
  37407. // Compute height
  37408. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37409. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37410. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37411. var r = options.buffer[pos] / 255.0;
  37412. var g = options.buffer[pos + 1] / 255.0;
  37413. var b = options.buffer[pos + 2] / 255.0;
  37414. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37415. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37416. // Add vertex
  37417. positions.push(position.x, position.y, position.z);
  37418. normals.push(0, 0, 0);
  37419. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37420. }
  37421. }
  37422. // Indices
  37423. for (row = 0; row < options.subdivisions; row++) {
  37424. for (col = 0; col < options.subdivisions; col++) {
  37425. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37426. indices.push(col + 1 + row * (options.subdivisions + 1));
  37427. indices.push(col + row * (options.subdivisions + 1));
  37428. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37429. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37430. indices.push(col + row * (options.subdivisions + 1));
  37431. }
  37432. }
  37433. // Normals
  37434. VertexData.ComputeNormals(positions, indices, normals);
  37435. // Result
  37436. var vertexData = new VertexData();
  37437. vertexData.indices = indices;
  37438. vertexData.positions = positions;
  37439. vertexData.normals = normals;
  37440. vertexData.uvs = uvs;
  37441. return vertexData;
  37442. };
  37443. /**
  37444. * Creates the VertexData for a Plane
  37445. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37446. * * size sets the width and height of the plane to the value of size, optional default 1
  37447. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37448. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37449. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37450. * * 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)
  37451. * * 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)
  37452. * @returns the VertexData of the box
  37453. */
  37454. VertexData.CreatePlane = function (options) {
  37455. var indices = [];
  37456. var positions = [];
  37457. var normals = [];
  37458. var uvs = [];
  37459. var width = options.width || options.size || 1;
  37460. var height = options.height || options.size || 1;
  37461. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37462. // Vertices
  37463. var halfWidth = width / 2.0;
  37464. var halfHeight = height / 2.0;
  37465. positions.push(-halfWidth, -halfHeight, 0);
  37466. normals.push(0, 0, -1.0);
  37467. uvs.push(0.0, 0.0);
  37468. positions.push(halfWidth, -halfHeight, 0);
  37469. normals.push(0, 0, -1.0);
  37470. uvs.push(1.0, 0.0);
  37471. positions.push(halfWidth, halfHeight, 0);
  37472. normals.push(0, 0, -1.0);
  37473. uvs.push(1.0, 1.0);
  37474. positions.push(-halfWidth, halfHeight, 0);
  37475. normals.push(0, 0, -1.0);
  37476. uvs.push(0.0, 1.0);
  37477. // Indices
  37478. indices.push(0);
  37479. indices.push(1);
  37480. indices.push(2);
  37481. indices.push(0);
  37482. indices.push(2);
  37483. indices.push(3);
  37484. // Sides
  37485. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37486. // Result
  37487. var vertexData = new VertexData();
  37488. vertexData.indices = indices;
  37489. vertexData.positions = positions;
  37490. vertexData.normals = normals;
  37491. vertexData.uvs = uvs;
  37492. return vertexData;
  37493. };
  37494. /**
  37495. * Creates the VertexData of the Disc or regular Polygon
  37496. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37497. * * radius the radius of the disc, optional default 0.5
  37498. * * tessellation the number of polygon sides, optional, default 64
  37499. * * 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
  37500. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37501. * * 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)
  37502. * * 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)
  37503. * @returns the VertexData of the box
  37504. */
  37505. VertexData.CreateDisc = function (options) {
  37506. var positions = new Array();
  37507. var indices = new Array();
  37508. var normals = new Array();
  37509. var uvs = new Array();
  37510. var radius = options.radius || 0.5;
  37511. var tessellation = options.tessellation || 64;
  37512. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37513. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37514. // positions and uvs
  37515. positions.push(0, 0, 0); // disc center first
  37516. uvs.push(0.5, 0.5);
  37517. var theta = Math.PI * 2 * arc;
  37518. var step = theta / tessellation;
  37519. for (var a = 0; a < theta; a += step) {
  37520. var x = Math.cos(a);
  37521. var y = Math.sin(a);
  37522. var u = (x + 1) / 2;
  37523. var v = (1 - y) / 2;
  37524. positions.push(radius * x, radius * y, 0);
  37525. uvs.push(u, v);
  37526. }
  37527. if (arc === 1) {
  37528. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37529. uvs.push(uvs[2], uvs[3]);
  37530. }
  37531. //indices
  37532. var vertexNb = positions.length / 3;
  37533. for (var i = 1; i < vertexNb - 1; i++) {
  37534. indices.push(i + 1, 0, i);
  37535. }
  37536. // result
  37537. VertexData.ComputeNormals(positions, indices, normals);
  37538. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37539. var vertexData = new VertexData();
  37540. vertexData.indices = indices;
  37541. vertexData.positions = positions;
  37542. vertexData.normals = normals;
  37543. vertexData.uvs = uvs;
  37544. return vertexData;
  37545. };
  37546. /**
  37547. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37548. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37549. * @param polygon a mesh built from polygonTriangulation.build()
  37550. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37551. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37552. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37553. * @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)
  37554. * @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)
  37555. * @returns the VertexData of the Polygon
  37556. */
  37557. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37558. var faceUV = fUV || new Array(3);
  37559. var faceColors = fColors;
  37560. var colors = [];
  37561. // default face colors and UV if undefined
  37562. for (var f = 0; f < 3; f++) {
  37563. if (faceUV[f] === undefined) {
  37564. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37565. }
  37566. if (faceColors && faceColors[f] === undefined) {
  37567. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37568. }
  37569. }
  37570. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37571. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37572. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37573. var indices = polygon.getIndices();
  37574. // set face colours and textures
  37575. var idx = 0;
  37576. var face = 0;
  37577. for (var index = 0; index < normals.length; index += 3) {
  37578. //Edge Face no. 1
  37579. if (Math.abs(normals[index + 1]) < 0.001) {
  37580. face = 1;
  37581. }
  37582. //Top Face no. 0
  37583. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37584. face = 0;
  37585. }
  37586. //Bottom Face no. 2
  37587. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37588. face = 2;
  37589. }
  37590. idx = index / 3;
  37591. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37592. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37593. if (faceColors) {
  37594. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37595. }
  37596. }
  37597. // sides
  37598. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37599. // Result
  37600. var vertexData = new VertexData();
  37601. vertexData.indices = indices;
  37602. vertexData.positions = positions;
  37603. vertexData.normals = normals;
  37604. vertexData.uvs = uvs;
  37605. if (faceColors) {
  37606. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37607. vertexData.colors = totalColors;
  37608. }
  37609. return vertexData;
  37610. };
  37611. /**
  37612. * Creates the VertexData of the IcoSphere
  37613. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37614. * * radius the radius of the IcoSphere, optional default 1
  37615. * * radiusX allows stretching in the x direction, optional, default radius
  37616. * * radiusY allows stretching in the y direction, optional, default radius
  37617. * * radiusZ allows stretching in the z direction, optional, default radius
  37618. * * flat when true creates a flat shaded mesh, optional, default true
  37619. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37620. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37621. * * 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)
  37622. * * 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)
  37623. * @returns the VertexData of the IcoSphere
  37624. */
  37625. VertexData.CreateIcoSphere = function (options) {
  37626. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37627. var radius = options.radius || 1;
  37628. var flat = (options.flat === undefined) ? true : options.flat;
  37629. var subdivisions = options.subdivisions || 4;
  37630. var radiusX = options.radiusX || radius;
  37631. var radiusY = options.radiusY || radius;
  37632. var radiusZ = options.radiusZ || radius;
  37633. var t = (1 + Math.sqrt(5)) / 2;
  37634. // 12 vertex x,y,z
  37635. var ico_vertices = [
  37636. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37637. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37638. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37639. ];
  37640. // index of 3 vertex makes a face of icopshere
  37641. var ico_indices = [
  37642. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37643. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37644. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37645. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37646. ];
  37647. // vertex for uv have aliased position, not for UV
  37648. var vertices_unalias_id = [
  37649. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37650. // vertex alias
  37651. 0,
  37652. 2,
  37653. 3,
  37654. 3,
  37655. 3,
  37656. 4,
  37657. 7,
  37658. 8,
  37659. 9,
  37660. 9,
  37661. 10,
  37662. 11 // 23: B + 12
  37663. ];
  37664. // uv as integer step (not pixels !)
  37665. var ico_vertexuv = [
  37666. 5, 1, 3, 1, 6, 4, 0, 0,
  37667. 5, 3, 4, 2, 2, 2, 4, 0,
  37668. 2, 0, 1, 1, 6, 0, 6, 2,
  37669. // vertex alias (for same vertex on different faces)
  37670. 0, 4,
  37671. 3, 3,
  37672. 4, 4,
  37673. 3, 1,
  37674. 4, 2,
  37675. 4, 4,
  37676. 0, 2,
  37677. 1, 1,
  37678. 2, 2,
  37679. 3, 3,
  37680. 1, 3,
  37681. 2, 4 // 23: B + 12
  37682. ];
  37683. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37684. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37685. // First island of uv mapping
  37686. // v = 4h 3+ 2
  37687. // v = 3h 9+ 4
  37688. // v = 2h 9+ 5 B
  37689. // v = 1h 9 1 0
  37690. // v = 0h 3 8 7 A
  37691. // u = 0 1 2 3 4 5 6 *a
  37692. // Second island of uv mapping
  37693. // v = 4h 0+ B+ 4+
  37694. // v = 3h A+ 2+
  37695. // v = 2h 7+ 6 3+
  37696. // v = 1h 8+ 3+
  37697. // v = 0h
  37698. // u = 0 1 2 3 4 5 6 *a
  37699. // Face layout on texture UV mapping
  37700. // ============
  37701. // \ 4 /\ 16 / ======
  37702. // \ / \ / /\ 11 /
  37703. // \/ 7 \/ / \ /
  37704. // ======= / 10 \/
  37705. // /\ 17 /\ =======
  37706. // / \ / \ \ 15 /\
  37707. // / 8 \/ 12 \ \ / \
  37708. // ============ \/ 6 \
  37709. // \ 18 /\ ============
  37710. // \ / \ \ 5 /\ 0 /
  37711. // \/ 13 \ \ / \ /
  37712. // ======= \/ 1 \/
  37713. // =============
  37714. // /\ 19 /\ 2 /\
  37715. // / \ / \ / \
  37716. // / 14 \/ 9 \/ 3 \
  37717. // ===================
  37718. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37719. var ustep = 138 / 1024;
  37720. var vstep = 239 / 1024;
  37721. var uoffset = 60 / 1024;
  37722. var voffset = 26 / 1024;
  37723. // Second island should have margin, not to touch the first island
  37724. // avoid any borderline artefact in pixel rounding
  37725. var island_u_offset = -40 / 1024;
  37726. var island_v_offset = +20 / 1024;
  37727. // face is either island 0 or 1 :
  37728. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37729. var island = [
  37730. 0, 0, 0, 0, 1,
  37731. 0, 0, 1, 1, 0,
  37732. 0, 0, 1, 1, 0,
  37733. 0, 1, 1, 1, 0 // 15 - 19
  37734. ];
  37735. var indices = new Array();
  37736. var positions = new Array();
  37737. var normals = new Array();
  37738. var uvs = new Array();
  37739. var current_indice = 0;
  37740. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37741. var face_vertex_pos = new Array(3);
  37742. var face_vertex_uv = new Array(3);
  37743. var v012;
  37744. for (v012 = 0; v012 < 3; v012++) {
  37745. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37746. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37747. }
  37748. // create all with normals
  37749. for (var face = 0; face < 20; face++) {
  37750. // 3 vertex per face
  37751. for (v012 = 0; v012 < 3; v012++) {
  37752. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37753. var v_id = ico_indices[3 * face + v012];
  37754. // vertex have 3D position (x,y,z)
  37755. 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]);
  37756. // Normalize to get normal, then scale to radius
  37757. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37758. // uv Coordinates from vertex ID
  37759. 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);
  37760. }
  37761. // Subdivide the face (interpolate pos, norm, uv)
  37762. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37763. // - norm is linear interpolation of vertex corner normal
  37764. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37765. // - uv is linear interpolation
  37766. //
  37767. // Topology is as below for sub-divide by 2
  37768. // vertex shown as v0,v1,v2
  37769. // interp index is i1 to progress in range [v0,v1[
  37770. // interp index is i2 to progress in range [v0,v2[
  37771. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37772. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37773. //
  37774. //
  37775. // i2 v2
  37776. // ^ ^
  37777. // / / \
  37778. // / / \
  37779. // / / \
  37780. // / / (0,1) \
  37781. // / #---------\
  37782. // / / \ (0,0)'/ \
  37783. // / / \ / \
  37784. // / / \ / \
  37785. // / / (0,0) \ / (1,0) \
  37786. // / #---------#---------\
  37787. // v0 v1
  37788. //
  37789. // --------------------> i1
  37790. //
  37791. // interp of (i1,i2):
  37792. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37793. // along i1 : lerp(x0,x1, i1/(S-i2))
  37794. //
  37795. // centroid of triangle is needed to get help normal computation
  37796. // (c1,c2) are used for centroid location
  37797. var interp_vertex = function (i1, i2, c1, c2) {
  37798. // vertex is interpolated from
  37799. // - face_vertex_pos[0..2]
  37800. // - face_vertex_uv[0..2]
  37801. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37802. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37803. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37804. pos_interp.normalize();
  37805. var vertex_normal;
  37806. if (flat) {
  37807. // in flat mode, recalculate normal as face centroid normal
  37808. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37809. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37810. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37811. }
  37812. else {
  37813. // in smooth mode, recalculate normal from each single vertex position
  37814. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37815. }
  37816. // Vertex normal need correction due to X,Y,Z radius scaling
  37817. vertex_normal.x /= radiusX;
  37818. vertex_normal.y /= radiusY;
  37819. vertex_normal.z /= radiusZ;
  37820. vertex_normal.normalize();
  37821. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37822. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37823. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37824. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37825. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37826. uvs.push(uv_interp.x, uv_interp.y);
  37827. // push each vertex has member of a face
  37828. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37829. indices.push(current_indice);
  37830. current_indice++;
  37831. };
  37832. for (var i2 = 0; i2 < subdivisions; i2++) {
  37833. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37834. // face : (i1,i2) for /\ :
  37835. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37836. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37837. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37838. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37839. if (i1 + i2 + 1 < subdivisions) {
  37840. // face : (i1,i2)' for \/ :
  37841. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37842. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37843. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37844. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37845. }
  37846. }
  37847. }
  37848. }
  37849. // Sides
  37850. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37851. // Result
  37852. var vertexData = new VertexData();
  37853. vertexData.indices = indices;
  37854. vertexData.positions = positions;
  37855. vertexData.normals = normals;
  37856. vertexData.uvs = uvs;
  37857. return vertexData;
  37858. };
  37859. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37860. /**
  37861. * Creates the VertexData for a Polyhedron
  37862. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37863. * * type provided types are:
  37864. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37865. * * 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)
  37866. * * size the size of the IcoSphere, optional default 1
  37867. * * sizeX allows stretching in the x direction, optional, default size
  37868. * * sizeY allows stretching in the y direction, optional, default size
  37869. * * sizeZ allows stretching in the z direction, optional, default size
  37870. * * 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
  37871. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37872. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37873. * * flat when true creates a flat shaded mesh, optional, default true
  37874. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37875. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37876. * * 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)
  37877. * * 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)
  37878. * @returns the VertexData of the Polyhedron
  37879. */
  37880. VertexData.CreatePolyhedron = function (options) {
  37881. // provided polyhedron types :
  37882. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37883. // 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)
  37884. var polyhedra = [];
  37885. 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]] };
  37886. 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]] };
  37887. polyhedra[2] = {
  37888. 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]],
  37889. 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]]
  37890. };
  37891. polyhedra[3] = {
  37892. 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]],
  37893. 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]]
  37894. };
  37895. polyhedra[4] = {
  37896. 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]],
  37897. 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]]
  37898. };
  37899. 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]] };
  37900. 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]] };
  37901. 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]] };
  37902. 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]] };
  37903. 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]] };
  37904. 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]] };
  37905. 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]] };
  37906. 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]] };
  37907. 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]] };
  37908. polyhedra[14] = {
  37909. 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]],
  37910. 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]]
  37911. };
  37912. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37913. var size = options.size;
  37914. var sizeX = options.sizeX || size || 1;
  37915. var sizeY = options.sizeY || size || 1;
  37916. var sizeZ = options.sizeZ || size || 1;
  37917. var data = options.custom || polyhedra[type];
  37918. var nbfaces = data.face.length;
  37919. var faceUV = options.faceUV || new Array(nbfaces);
  37920. var faceColors = options.faceColors;
  37921. var flat = (options.flat === undefined) ? true : options.flat;
  37922. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37923. var positions = new Array();
  37924. var indices = new Array();
  37925. var normals = new Array();
  37926. var uvs = new Array();
  37927. var colors = new Array();
  37928. var index = 0;
  37929. var faceIdx = 0; // face cursor in the array "indexes"
  37930. var indexes = new Array();
  37931. var i = 0;
  37932. var f = 0;
  37933. var u, v, ang, x, y, tmp;
  37934. // default face colors and UV if undefined
  37935. if (flat) {
  37936. for (f = 0; f < nbfaces; f++) {
  37937. if (faceColors && faceColors[f] === undefined) {
  37938. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37939. }
  37940. if (faceUV && faceUV[f] === undefined) {
  37941. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37942. }
  37943. }
  37944. }
  37945. if (!flat) {
  37946. for (i = 0; i < data.vertex.length; i++) {
  37947. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37948. uvs.push(0, 0);
  37949. }
  37950. for (f = 0; f < nbfaces; f++) {
  37951. for (i = 0; i < data.face[f].length - 2; i++) {
  37952. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37953. }
  37954. }
  37955. }
  37956. else {
  37957. for (f = 0; f < nbfaces; f++) {
  37958. var fl = data.face[f].length; // number of vertices of the current face
  37959. ang = 2 * Math.PI / fl;
  37960. x = 0.5 * Math.tan(ang / 2);
  37961. y = 0.5;
  37962. // positions, uvs, colors
  37963. for (i = 0; i < fl; i++) {
  37964. // positions
  37965. 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);
  37966. indexes.push(index);
  37967. index++;
  37968. // uvs
  37969. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37970. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37971. uvs.push(u, v);
  37972. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37973. y = x * Math.sin(ang) + y * Math.cos(ang);
  37974. x = tmp;
  37975. // colors
  37976. if (faceColors) {
  37977. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37978. }
  37979. }
  37980. // indices from indexes
  37981. for (i = 0; i < fl - 2; i++) {
  37982. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37983. }
  37984. faceIdx += fl;
  37985. }
  37986. }
  37987. VertexData.ComputeNormals(positions, indices, normals);
  37988. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37989. var vertexData = new VertexData();
  37990. vertexData.positions = positions;
  37991. vertexData.indices = indices;
  37992. vertexData.normals = normals;
  37993. vertexData.uvs = uvs;
  37994. if (faceColors && flat) {
  37995. vertexData.colors = colors;
  37996. }
  37997. return vertexData;
  37998. };
  37999. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38000. /**
  38001. * Creates the VertexData for a TorusKnot
  38002. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38003. * * radius the radius of the torus knot, optional, default 2
  38004. * * tube the thickness of the tube, optional, default 0.5
  38005. * * radialSegments the number of sides on each tube segments, optional, default 32
  38006. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38007. * * p the number of windings around the z axis, optional, default 2
  38008. * * q the number of windings around the x axis, optional, default 3
  38009. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38010. * * 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)
  38011. * * 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)
  38012. * @returns the VertexData of the Torus Knot
  38013. */
  38014. VertexData.CreateTorusKnot = function (options) {
  38015. var indices = new Array();
  38016. var positions = new Array();
  38017. var normals = new Array();
  38018. var uvs = new Array();
  38019. var radius = options.radius || 2;
  38020. var tube = options.tube || 0.5;
  38021. var radialSegments = options.radialSegments || 32;
  38022. var tubularSegments = options.tubularSegments || 32;
  38023. var p = options.p || 2;
  38024. var q = options.q || 3;
  38025. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38026. // Helper
  38027. var getPos = function (angle) {
  38028. var cu = Math.cos(angle);
  38029. var su = Math.sin(angle);
  38030. var quOverP = q / p * angle;
  38031. var cs = Math.cos(quOverP);
  38032. var tx = radius * (2 + cs) * 0.5 * cu;
  38033. var ty = radius * (2 + cs) * su * 0.5;
  38034. var tz = radius * Math.sin(quOverP) * 0.5;
  38035. return new BABYLON.Vector3(tx, ty, tz);
  38036. };
  38037. // Vertices
  38038. var i;
  38039. var j;
  38040. for (i = 0; i <= radialSegments; i++) {
  38041. var modI = i % radialSegments;
  38042. var u = modI / radialSegments * 2 * p * Math.PI;
  38043. var p1 = getPos(u);
  38044. var p2 = getPos(u + 0.01);
  38045. var tang = p2.subtract(p1);
  38046. var n = p2.add(p1);
  38047. var bitan = BABYLON.Vector3.Cross(tang, n);
  38048. n = BABYLON.Vector3.Cross(bitan, tang);
  38049. bitan.normalize();
  38050. n.normalize();
  38051. for (j = 0; j < tubularSegments; j++) {
  38052. var modJ = j % tubularSegments;
  38053. var v = modJ / tubularSegments * 2 * Math.PI;
  38054. var cx = -tube * Math.cos(v);
  38055. var cy = tube * Math.sin(v);
  38056. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38057. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38058. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38059. uvs.push(i / radialSegments);
  38060. uvs.push(j / tubularSegments);
  38061. }
  38062. }
  38063. for (i = 0; i < radialSegments; i++) {
  38064. for (j = 0; j < tubularSegments; j++) {
  38065. var jNext = (j + 1) % tubularSegments;
  38066. var a = i * tubularSegments + j;
  38067. var b = (i + 1) * tubularSegments + j;
  38068. var c = (i + 1) * tubularSegments + jNext;
  38069. var d = i * tubularSegments + jNext;
  38070. indices.push(d);
  38071. indices.push(b);
  38072. indices.push(a);
  38073. indices.push(d);
  38074. indices.push(c);
  38075. indices.push(b);
  38076. }
  38077. }
  38078. // Normals
  38079. VertexData.ComputeNormals(positions, indices, normals);
  38080. // Sides
  38081. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38082. // Result
  38083. var vertexData = new VertexData();
  38084. vertexData.indices = indices;
  38085. vertexData.positions = positions;
  38086. vertexData.normals = normals;
  38087. vertexData.uvs = uvs;
  38088. return vertexData;
  38089. };
  38090. // Tools
  38091. /**
  38092. * Compute normals for given positions and indices
  38093. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38094. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38095. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38096. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38097. * * facetNormals : optional array of facet normals (vector3)
  38098. * * facetPositions : optional array of facet positions (vector3)
  38099. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38100. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38101. * * bInfo : optional bounding info, required for facetPartitioning computation
  38102. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38103. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38104. * * useRightHandedSystem: optional boolean to for right handed system computation
  38105. * * depthSort : optional boolean to enable the facet depth sort computation
  38106. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38107. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38108. */
  38109. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38110. // temporary scalar variables
  38111. var index = 0; // facet index
  38112. var p1p2x = 0.0; // p1p2 vector x coordinate
  38113. var p1p2y = 0.0; // p1p2 vector y coordinate
  38114. var p1p2z = 0.0; // p1p2 vector z coordinate
  38115. var p3p2x = 0.0; // p3p2 vector x coordinate
  38116. var p3p2y = 0.0; // p3p2 vector y coordinate
  38117. var p3p2z = 0.0; // p3p2 vector z coordinate
  38118. var faceNormalx = 0.0; // facet normal x coordinate
  38119. var faceNormaly = 0.0; // facet normal y coordinate
  38120. var faceNormalz = 0.0; // facet normal z coordinate
  38121. var length = 0.0; // facet normal length before normalization
  38122. var v1x = 0; // vector1 x index in the positions array
  38123. var v1y = 0; // vector1 y index in the positions array
  38124. var v1z = 0; // vector1 z index in the positions array
  38125. var v2x = 0; // vector2 x index in the positions array
  38126. var v2y = 0; // vector2 y index in the positions array
  38127. var v2z = 0; // vector2 z index in the positions array
  38128. var v3x = 0; // vector3 x index in the positions array
  38129. var v3y = 0; // vector3 y index in the positions array
  38130. var v3z = 0; // vector3 z index in the positions array
  38131. var computeFacetNormals = false;
  38132. var computeFacetPositions = false;
  38133. var computeFacetPartitioning = false;
  38134. var computeDepthSort = false;
  38135. var faceNormalSign = 1;
  38136. var ratio = 0;
  38137. var distanceTo = null;
  38138. if (options) {
  38139. computeFacetNormals = (options.facetNormals) ? true : false;
  38140. computeFacetPositions = (options.facetPositions) ? true : false;
  38141. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38142. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38143. ratio = options.ratio || 0;
  38144. computeDepthSort = (options.depthSort) ? true : false;
  38145. distanceTo = (options.distanceTo);
  38146. if (computeDepthSort) {
  38147. if (distanceTo === undefined) {
  38148. distanceTo = BABYLON.Vector3.Zero();
  38149. }
  38150. var depthSortedFacets = options.depthSortedFacets;
  38151. }
  38152. }
  38153. // facetPartitioning reinit if needed
  38154. var xSubRatio = 0;
  38155. var ySubRatio = 0;
  38156. var zSubRatio = 0;
  38157. var subSq = 0;
  38158. if (computeFacetPartitioning && options && options.bbSize) {
  38159. var ox = 0; // X partitioning index for facet position
  38160. var oy = 0; // Y partinioning index for facet position
  38161. var oz = 0; // Z partinioning index for facet position
  38162. var b1x = 0; // X partitioning index for facet v1 vertex
  38163. var b1y = 0; // Y partitioning index for facet v1 vertex
  38164. var b1z = 0; // z partitioning index for facet v1 vertex
  38165. var b2x = 0; // X partitioning index for facet v2 vertex
  38166. var b2y = 0; // Y partitioning index for facet v2 vertex
  38167. var b2z = 0; // Z partitioning index for facet v2 vertex
  38168. var b3x = 0; // X partitioning index for facet v3 vertex
  38169. var b3y = 0; // Y partitioning index for facet v3 vertex
  38170. var b3z = 0; // Z partitioning index for facet v3 vertex
  38171. var block_idx_o = 0; // facet barycenter block index
  38172. var block_idx_v1 = 0; // v1 vertex block index
  38173. var block_idx_v2 = 0; // v2 vertex block index
  38174. var block_idx_v3 = 0; // v3 vertex block index
  38175. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38176. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38177. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38178. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38179. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38180. subSq = options.subDiv.max * options.subDiv.max;
  38181. options.facetPartitioning.length = 0;
  38182. }
  38183. // reset the normals
  38184. for (index = 0; index < positions.length; index++) {
  38185. normals[index] = 0.0;
  38186. }
  38187. // Loop : 1 indice triplet = 1 facet
  38188. var nbFaces = (indices.length / 3) | 0;
  38189. for (index = 0; index < nbFaces; index++) {
  38190. // get the indexes of the coordinates of each vertex of the facet
  38191. v1x = indices[index * 3] * 3;
  38192. v1y = v1x + 1;
  38193. v1z = v1x + 2;
  38194. v2x = indices[index * 3 + 1] * 3;
  38195. v2y = v2x + 1;
  38196. v2z = v2x + 2;
  38197. v3x = indices[index * 3 + 2] * 3;
  38198. v3y = v3x + 1;
  38199. v3z = v3x + 2;
  38200. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38201. p1p2y = positions[v1y] - positions[v2y];
  38202. p1p2z = positions[v1z] - positions[v2z];
  38203. p3p2x = positions[v3x] - positions[v2x];
  38204. p3p2y = positions[v3y] - positions[v2y];
  38205. p3p2z = positions[v3z] - positions[v2z];
  38206. // compute the face normal with the cross product
  38207. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38208. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38209. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38210. // normalize this normal and store it in the array facetData
  38211. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38212. length = (length === 0) ? 1.0 : length;
  38213. faceNormalx /= length;
  38214. faceNormaly /= length;
  38215. faceNormalz /= length;
  38216. if (computeFacetNormals && options) {
  38217. options.facetNormals[index].x = faceNormalx;
  38218. options.facetNormals[index].y = faceNormaly;
  38219. options.facetNormals[index].z = faceNormalz;
  38220. }
  38221. if (computeFacetPositions && options) {
  38222. // compute and the facet barycenter coordinates in the array facetPositions
  38223. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38224. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38225. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38226. }
  38227. if (computeFacetPartitioning && options) {
  38228. // store the facet indexes in arrays in the main facetPartitioning array :
  38229. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38230. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38231. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38232. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38233. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38234. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38235. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38236. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38237. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38238. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38239. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38240. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38241. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38242. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38243. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38244. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38245. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38246. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38247. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38248. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38249. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38250. // push each facet index in each block containing the vertex
  38251. options.facetPartitioning[block_idx_v1].push(index);
  38252. if (block_idx_v2 != block_idx_v1) {
  38253. options.facetPartitioning[block_idx_v2].push(index);
  38254. }
  38255. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38256. options.facetPartitioning[block_idx_v3].push(index);
  38257. }
  38258. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38259. options.facetPartitioning[block_idx_o].push(index);
  38260. }
  38261. }
  38262. if (computeDepthSort && options && options.facetPositions) {
  38263. var dsf = depthSortedFacets[index];
  38264. dsf.ind = index * 3;
  38265. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38266. }
  38267. // compute the normals anyway
  38268. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38269. normals[v1y] += faceNormaly;
  38270. normals[v1z] += faceNormalz;
  38271. normals[v2x] += faceNormalx;
  38272. normals[v2y] += faceNormaly;
  38273. normals[v2z] += faceNormalz;
  38274. normals[v3x] += faceNormalx;
  38275. normals[v3y] += faceNormaly;
  38276. normals[v3z] += faceNormalz;
  38277. }
  38278. // last normalization of each normal
  38279. for (index = 0; index < normals.length / 3; index++) {
  38280. faceNormalx = normals[index * 3];
  38281. faceNormaly = normals[index * 3 + 1];
  38282. faceNormalz = normals[index * 3 + 2];
  38283. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38284. length = (length === 0) ? 1.0 : length;
  38285. faceNormalx /= length;
  38286. faceNormaly /= length;
  38287. faceNormalz /= length;
  38288. normals[index * 3] = faceNormalx;
  38289. normals[index * 3 + 1] = faceNormaly;
  38290. normals[index * 3 + 2] = faceNormalz;
  38291. }
  38292. };
  38293. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38294. var li = indices.length;
  38295. var ln = normals.length;
  38296. var i;
  38297. var n;
  38298. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38299. switch (sideOrientation) {
  38300. case BABYLON.Mesh.FRONTSIDE:
  38301. // nothing changed
  38302. break;
  38303. case BABYLON.Mesh.BACKSIDE:
  38304. var tmp;
  38305. // indices
  38306. for (i = 0; i < li; i += 3) {
  38307. tmp = indices[i];
  38308. indices[i] = indices[i + 2];
  38309. indices[i + 2] = tmp;
  38310. }
  38311. // normals
  38312. for (n = 0; n < ln; n++) {
  38313. normals[n] = -normals[n];
  38314. }
  38315. break;
  38316. case BABYLON.Mesh.DOUBLESIDE:
  38317. // positions
  38318. var lp = positions.length;
  38319. var l = lp / 3;
  38320. for (var p = 0; p < lp; p++) {
  38321. positions[lp + p] = positions[p];
  38322. }
  38323. // indices
  38324. for (i = 0; i < li; i += 3) {
  38325. indices[i + li] = indices[i + 2] + l;
  38326. indices[i + 1 + li] = indices[i + 1] + l;
  38327. indices[i + 2 + li] = indices[i] + l;
  38328. }
  38329. // normals
  38330. for (n = 0; n < ln; n++) {
  38331. normals[ln + n] = -normals[n];
  38332. }
  38333. // uvs
  38334. var lu = uvs.length;
  38335. var u = 0;
  38336. for (u = 0; u < lu; u++) {
  38337. uvs[u + lu] = uvs[u];
  38338. }
  38339. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38340. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38341. u = 0;
  38342. for (i = 0; i < lu / 2; i++) {
  38343. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38344. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38345. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38346. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38347. u += 2;
  38348. }
  38349. break;
  38350. }
  38351. };
  38352. /**
  38353. * Applies VertexData created from the imported parameters to the geometry
  38354. * @param parsedVertexData the parsed data from an imported file
  38355. * @param geometry the geometry to apply the VertexData to
  38356. */
  38357. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38358. var vertexData = new VertexData();
  38359. // positions
  38360. var positions = parsedVertexData.positions;
  38361. if (positions) {
  38362. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38363. }
  38364. // normals
  38365. var normals = parsedVertexData.normals;
  38366. if (normals) {
  38367. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38368. }
  38369. // tangents
  38370. var tangents = parsedVertexData.tangents;
  38371. if (tangents) {
  38372. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38373. }
  38374. // uvs
  38375. var uvs = parsedVertexData.uvs;
  38376. if (uvs) {
  38377. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38378. }
  38379. // uv2s
  38380. var uv2s = parsedVertexData.uv2s;
  38381. if (uv2s) {
  38382. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38383. }
  38384. // uv3s
  38385. var uv3s = parsedVertexData.uv3s;
  38386. if (uv3s) {
  38387. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38388. }
  38389. // uv4s
  38390. var uv4s = parsedVertexData.uv4s;
  38391. if (uv4s) {
  38392. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38393. }
  38394. // uv5s
  38395. var uv5s = parsedVertexData.uv5s;
  38396. if (uv5s) {
  38397. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38398. }
  38399. // uv6s
  38400. var uv6s = parsedVertexData.uv6s;
  38401. if (uv6s) {
  38402. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38403. }
  38404. // colors
  38405. var colors = parsedVertexData.colors;
  38406. if (colors) {
  38407. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38408. }
  38409. // matricesIndices
  38410. var matricesIndices = parsedVertexData.matricesIndices;
  38411. if (matricesIndices) {
  38412. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38413. }
  38414. // matricesWeights
  38415. var matricesWeights = parsedVertexData.matricesWeights;
  38416. if (matricesWeights) {
  38417. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38418. }
  38419. // indices
  38420. var indices = parsedVertexData.indices;
  38421. if (indices) {
  38422. vertexData.indices = indices;
  38423. }
  38424. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38425. };
  38426. return VertexData;
  38427. }());
  38428. BABYLON.VertexData = VertexData;
  38429. })(BABYLON || (BABYLON = {}));
  38430. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38431. var BABYLON;
  38432. (function (BABYLON) {
  38433. /**
  38434. * Class used to store geometry data (vertex buffers + index buffer)
  38435. */
  38436. var Geometry = /** @class */ (function () {
  38437. /**
  38438. * Creates a new geometry
  38439. * @param id defines the unique ID
  38440. * @param scene defines the hosting scene
  38441. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38442. * @param updatable defines if geometry must be updatable (false by default)
  38443. * @param mesh defines the mesh that will be associated with the geometry
  38444. */
  38445. function Geometry(id, scene, vertexData, updatable, mesh) {
  38446. if (updatable === void 0) { updatable = false; }
  38447. if (mesh === void 0) { mesh = null; }
  38448. /**
  38449. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38450. */
  38451. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38452. this._totalVertices = 0;
  38453. this._isDisposed = false;
  38454. this._indexBufferIsUpdatable = false;
  38455. this.id = id;
  38456. this._engine = scene.getEngine();
  38457. this._meshes = [];
  38458. this._scene = scene;
  38459. //Init vertex buffer cache
  38460. this._vertexBuffers = {};
  38461. this._indices = [];
  38462. this._updatable = updatable;
  38463. // vertexData
  38464. if (vertexData) {
  38465. this.setAllVerticesData(vertexData, updatable);
  38466. }
  38467. else {
  38468. this._totalVertices = 0;
  38469. this._indices = [];
  38470. }
  38471. if (this._engine.getCaps().vertexArrayObject) {
  38472. this._vertexArrayObjects = {};
  38473. }
  38474. // applyToMesh
  38475. if (mesh) {
  38476. if (mesh.getClassName() === "LinesMesh") {
  38477. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38478. this._updateExtend();
  38479. }
  38480. this.applyToMesh(mesh);
  38481. mesh.computeWorldMatrix(true);
  38482. }
  38483. }
  38484. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38485. /**
  38486. * 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
  38487. */
  38488. get: function () {
  38489. return this._boundingBias;
  38490. },
  38491. /**
  38492. * 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
  38493. */
  38494. set: function (value) {
  38495. if (this._boundingBias && this._boundingBias.equals(value)) {
  38496. return;
  38497. }
  38498. this._boundingBias = value.clone();
  38499. this._updateBoundingInfo(true, null);
  38500. },
  38501. enumerable: true,
  38502. configurable: true
  38503. });
  38504. /**
  38505. * Static function used to attach a new empty geometry to a mesh
  38506. * @param mesh defines the mesh to attach the geometry to
  38507. * @returns the new {BABYLON.Geometry}
  38508. */
  38509. Geometry.CreateGeometryForMesh = function (mesh) {
  38510. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38511. geometry.applyToMesh(mesh);
  38512. return geometry;
  38513. };
  38514. Object.defineProperty(Geometry.prototype, "extend", {
  38515. /**
  38516. * Gets the current extend of the geometry
  38517. */
  38518. get: function () {
  38519. return this._extend;
  38520. },
  38521. enumerable: true,
  38522. configurable: true
  38523. });
  38524. /**
  38525. * Gets the hosting scene
  38526. * @returns the hosting {BABYLON.Scene}
  38527. */
  38528. Geometry.prototype.getScene = function () {
  38529. return this._scene;
  38530. };
  38531. /**
  38532. * Gets the hosting engine
  38533. * @returns the hosting {BABYLON.Engine}
  38534. */
  38535. Geometry.prototype.getEngine = function () {
  38536. return this._engine;
  38537. };
  38538. /**
  38539. * Defines if the geometry is ready to use
  38540. * @returns true if the geometry is ready to be used
  38541. */
  38542. Geometry.prototype.isReady = function () {
  38543. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38544. };
  38545. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38546. /**
  38547. * Gets a value indicating that the geometry should not be serialized
  38548. */
  38549. get: function () {
  38550. for (var index = 0; index < this._meshes.length; index++) {
  38551. if (!this._meshes[index].doNotSerialize) {
  38552. return false;
  38553. }
  38554. }
  38555. return true;
  38556. },
  38557. enumerable: true,
  38558. configurable: true
  38559. });
  38560. /** @hidden */
  38561. Geometry.prototype._rebuild = function () {
  38562. if (this._vertexArrayObjects) {
  38563. this._vertexArrayObjects = {};
  38564. }
  38565. // Index buffer
  38566. if (this._meshes.length !== 0 && this._indices) {
  38567. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38568. }
  38569. // Vertex buffers
  38570. for (var key in this._vertexBuffers) {
  38571. var vertexBuffer = this._vertexBuffers[key];
  38572. vertexBuffer._rebuild();
  38573. }
  38574. };
  38575. /**
  38576. * Affects all geometry data in one call
  38577. * @param vertexData defines the geometry data
  38578. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38579. */
  38580. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38581. vertexData.applyToGeometry(this, updatable);
  38582. this.notifyUpdate();
  38583. };
  38584. /**
  38585. * Set specific vertex data
  38586. * @param kind defines the data kind (Position, normal, etc...)
  38587. * @param data defines the vertex data to use
  38588. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38589. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38590. */
  38591. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38592. if (updatable === void 0) { updatable = false; }
  38593. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38594. this.setVerticesBuffer(buffer);
  38595. };
  38596. /**
  38597. * Removes a specific vertex data
  38598. * @param kind defines the data kind (Position, normal, etc...)
  38599. */
  38600. Geometry.prototype.removeVerticesData = function (kind) {
  38601. if (this._vertexBuffers[kind]) {
  38602. this._vertexBuffers[kind].dispose();
  38603. delete this._vertexBuffers[kind];
  38604. }
  38605. };
  38606. /**
  38607. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38608. * @param buffer defines the vertex buffer to use
  38609. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38610. */
  38611. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38612. if (totalVertices === void 0) { totalVertices = null; }
  38613. var kind = buffer.getKind();
  38614. if (this._vertexBuffers[kind]) {
  38615. this._vertexBuffers[kind].dispose();
  38616. }
  38617. this._vertexBuffers[kind] = buffer;
  38618. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38619. var data = buffer.getData();
  38620. if (totalVertices != null) {
  38621. this._totalVertices = totalVertices;
  38622. }
  38623. else {
  38624. if (data != null) {
  38625. this._totalVertices = data.length / (buffer.byteStride / 4);
  38626. }
  38627. }
  38628. this._updateExtend(data);
  38629. this._resetPointsArrayCache();
  38630. var meshes = this._meshes;
  38631. var numOfMeshes = meshes.length;
  38632. for (var index = 0; index < numOfMeshes; index++) {
  38633. var mesh = meshes[index];
  38634. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38635. mesh._createGlobalSubMesh(false);
  38636. mesh.computeWorldMatrix(true);
  38637. }
  38638. }
  38639. this.notifyUpdate(kind);
  38640. if (this._vertexArrayObjects) {
  38641. this._disposeVertexArrayObjects();
  38642. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38643. }
  38644. };
  38645. /**
  38646. * Update a specific vertex buffer
  38647. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38648. * It will do nothing if the buffer is not updatable
  38649. * @param kind defines the data kind (Position, normal, etc...)
  38650. * @param data defines the data to use
  38651. * @param offset defines the offset in the target buffer where to store the data
  38652. * @param useBytes set to true if the offset is in bytes
  38653. */
  38654. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38655. if (useBytes === void 0) { useBytes = false; }
  38656. var vertexBuffer = this.getVertexBuffer(kind);
  38657. if (!vertexBuffer) {
  38658. return;
  38659. }
  38660. vertexBuffer.updateDirectly(data, offset, useBytes);
  38661. this.notifyUpdate(kind);
  38662. };
  38663. /**
  38664. * Update a specific vertex buffer
  38665. * This function will create a new buffer if the current one is not updatable
  38666. * @param kind defines the data kind (Position, normal, etc...)
  38667. * @param data defines the data to use
  38668. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38669. */
  38670. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38671. if (updateExtends === void 0) { updateExtends = false; }
  38672. var vertexBuffer = this.getVertexBuffer(kind);
  38673. if (!vertexBuffer) {
  38674. return;
  38675. }
  38676. vertexBuffer.update(data);
  38677. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38678. this._updateBoundingInfo(updateExtends, data);
  38679. }
  38680. this.notifyUpdate(kind);
  38681. };
  38682. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38683. if (updateExtends) {
  38684. this._updateExtend(data);
  38685. }
  38686. var meshes = this._meshes;
  38687. var numOfMeshes = meshes.length;
  38688. this._resetPointsArrayCache();
  38689. for (var index = 0; index < numOfMeshes; index++) {
  38690. var mesh = meshes[index];
  38691. if (updateExtends) {
  38692. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38693. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38694. var subMesh = mesh.subMeshes[subIndex];
  38695. subMesh.refreshBoundingInfo();
  38696. }
  38697. }
  38698. }
  38699. };
  38700. /** @hidden */
  38701. Geometry.prototype._bind = function (effect, indexToBind) {
  38702. if (!effect) {
  38703. return;
  38704. }
  38705. if (indexToBind === undefined) {
  38706. indexToBind = this._indexBuffer;
  38707. }
  38708. var vbs = this.getVertexBuffers();
  38709. if (!vbs) {
  38710. return;
  38711. }
  38712. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38713. this._engine.bindBuffers(vbs, indexToBind, effect);
  38714. return;
  38715. }
  38716. // Using VAO
  38717. if (!this._vertexArrayObjects[effect.key]) {
  38718. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38719. }
  38720. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38721. };
  38722. /**
  38723. * Gets total number of vertices
  38724. * @returns the total number of vertices
  38725. */
  38726. Geometry.prototype.getTotalVertices = function () {
  38727. if (!this.isReady()) {
  38728. return 0;
  38729. }
  38730. return this._totalVertices;
  38731. };
  38732. /**
  38733. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38734. * @param kind defines the data kind (Position, normal, etc...)
  38735. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38736. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38737. * @returns a float array containing vertex data
  38738. */
  38739. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38740. var vertexBuffer = this.getVertexBuffer(kind);
  38741. if (!vertexBuffer) {
  38742. return null;
  38743. }
  38744. var data = vertexBuffer.getData();
  38745. if (!data) {
  38746. return null;
  38747. }
  38748. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38749. var count = this._totalVertices * vertexBuffer.getSize();
  38750. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38751. var copy_1 = new Array(count);
  38752. vertexBuffer.forEach(count, function (value, index) {
  38753. copy_1[index] = value;
  38754. });
  38755. return copy_1;
  38756. }
  38757. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38758. if (data instanceof Array) {
  38759. var offset = vertexBuffer.byteOffset / 4;
  38760. return BABYLON.Tools.Slice(data, offset, offset + count);
  38761. }
  38762. else if (data instanceof ArrayBuffer) {
  38763. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38764. }
  38765. else {
  38766. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38767. }
  38768. }
  38769. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38770. return BABYLON.Tools.Slice(data);
  38771. }
  38772. return data;
  38773. };
  38774. /**
  38775. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38776. * @param kind defines the data kind (Position, normal, etc...)
  38777. * @returns true if the vertex buffer with the specified kind is updatable
  38778. */
  38779. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38780. var vb = this._vertexBuffers[kind];
  38781. if (!vb) {
  38782. return false;
  38783. }
  38784. return vb.isUpdatable();
  38785. };
  38786. /**
  38787. * Gets a specific vertex buffer
  38788. * @param kind defines the data kind (Position, normal, etc...)
  38789. * @returns a {BABYLON.VertexBuffer}
  38790. */
  38791. Geometry.prototype.getVertexBuffer = function (kind) {
  38792. if (!this.isReady()) {
  38793. return null;
  38794. }
  38795. return this._vertexBuffers[kind];
  38796. };
  38797. /**
  38798. * Returns all vertex buffers
  38799. * @return an object holding all vertex buffers indexed by kind
  38800. */
  38801. Geometry.prototype.getVertexBuffers = function () {
  38802. if (!this.isReady()) {
  38803. return null;
  38804. }
  38805. return this._vertexBuffers;
  38806. };
  38807. /**
  38808. * Gets a boolean indicating if specific vertex buffer is present
  38809. * @param kind defines the data kind (Position, normal, etc...)
  38810. * @returns true if data is present
  38811. */
  38812. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38813. if (!this._vertexBuffers) {
  38814. if (this._delayInfo) {
  38815. return this._delayInfo.indexOf(kind) !== -1;
  38816. }
  38817. return false;
  38818. }
  38819. return this._vertexBuffers[kind] !== undefined;
  38820. };
  38821. /**
  38822. * Gets a list of all attached data kinds (Position, normal, etc...)
  38823. * @returns a list of string containing all kinds
  38824. */
  38825. Geometry.prototype.getVerticesDataKinds = function () {
  38826. var result = [];
  38827. var kind;
  38828. if (!this._vertexBuffers && this._delayInfo) {
  38829. for (kind in this._delayInfo) {
  38830. result.push(kind);
  38831. }
  38832. }
  38833. else {
  38834. for (kind in this._vertexBuffers) {
  38835. result.push(kind);
  38836. }
  38837. }
  38838. return result;
  38839. };
  38840. /**
  38841. * Update index buffer
  38842. * @param indices defines the indices to store in the index buffer
  38843. * @param offset defines the offset in the target buffer where to store the data
  38844. */
  38845. Geometry.prototype.updateIndices = function (indices, offset) {
  38846. if (!this._indexBuffer) {
  38847. return;
  38848. }
  38849. if (!this._indexBufferIsUpdatable) {
  38850. this.setIndices(indices, null, true);
  38851. }
  38852. else {
  38853. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38854. }
  38855. };
  38856. /**
  38857. * Creates a new index buffer
  38858. * @param indices defines the indices to store in the index buffer
  38859. * @param totalVertices defines the total number of vertices (could be null)
  38860. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38861. */
  38862. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38863. if (totalVertices === void 0) { totalVertices = null; }
  38864. if (updatable === void 0) { updatable = false; }
  38865. if (this._indexBuffer) {
  38866. this._engine._releaseBuffer(this._indexBuffer);
  38867. }
  38868. this._disposeVertexArrayObjects();
  38869. this._indices = indices;
  38870. this._indexBufferIsUpdatable = updatable;
  38871. if (this._meshes.length !== 0 && this._indices) {
  38872. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38873. }
  38874. if (totalVertices != undefined) { // including null and undefined
  38875. this._totalVertices = totalVertices;
  38876. }
  38877. var meshes = this._meshes;
  38878. var numOfMeshes = meshes.length;
  38879. for (var index = 0; index < numOfMeshes; index++) {
  38880. meshes[index]._createGlobalSubMesh(true);
  38881. }
  38882. this.notifyUpdate();
  38883. };
  38884. /**
  38885. * Return the total number of indices
  38886. * @returns the total number of indices
  38887. */
  38888. Geometry.prototype.getTotalIndices = function () {
  38889. if (!this.isReady()) {
  38890. return 0;
  38891. }
  38892. return this._indices.length;
  38893. };
  38894. /**
  38895. * Gets the index buffer array
  38896. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38897. * @returns the index buffer array
  38898. */
  38899. Geometry.prototype.getIndices = function (copyWhenShared) {
  38900. if (!this.isReady()) {
  38901. return null;
  38902. }
  38903. var orig = this._indices;
  38904. if (!copyWhenShared || this._meshes.length === 1) {
  38905. return orig;
  38906. }
  38907. else {
  38908. var len = orig.length;
  38909. var copy = [];
  38910. for (var i = 0; i < len; i++) {
  38911. copy.push(orig[i]);
  38912. }
  38913. return copy;
  38914. }
  38915. };
  38916. /**
  38917. * Gets the index buffer
  38918. * @return the index buffer
  38919. */
  38920. Geometry.prototype.getIndexBuffer = function () {
  38921. if (!this.isReady()) {
  38922. return null;
  38923. }
  38924. return this._indexBuffer;
  38925. };
  38926. /** @hidden */
  38927. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38928. if (effect === void 0) { effect = null; }
  38929. if (!effect || !this._vertexArrayObjects) {
  38930. return;
  38931. }
  38932. if (this._vertexArrayObjects[effect.key]) {
  38933. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38934. delete this._vertexArrayObjects[effect.key];
  38935. }
  38936. };
  38937. /**
  38938. * Release the associated resources for a specific mesh
  38939. * @param mesh defines the source mesh
  38940. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38941. */
  38942. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38943. var meshes = this._meshes;
  38944. var index = meshes.indexOf(mesh);
  38945. if (index === -1) {
  38946. return;
  38947. }
  38948. meshes.splice(index, 1);
  38949. mesh._geometry = null;
  38950. if (meshes.length === 0 && shouldDispose) {
  38951. this.dispose();
  38952. }
  38953. };
  38954. /**
  38955. * Apply current geometry to a given mesh
  38956. * @param mesh defines the mesh to apply geometry to
  38957. */
  38958. Geometry.prototype.applyToMesh = function (mesh) {
  38959. if (mesh._geometry === this) {
  38960. return;
  38961. }
  38962. var previousGeometry = mesh._geometry;
  38963. if (previousGeometry) {
  38964. previousGeometry.releaseForMesh(mesh);
  38965. }
  38966. var meshes = this._meshes;
  38967. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38968. mesh._geometry = this;
  38969. this._scene.pushGeometry(this);
  38970. meshes.push(mesh);
  38971. if (this.isReady()) {
  38972. this._applyToMesh(mesh);
  38973. }
  38974. else {
  38975. mesh._boundingInfo = this._boundingInfo;
  38976. }
  38977. };
  38978. Geometry.prototype._updateExtend = function (data) {
  38979. if (data === void 0) { data = null; }
  38980. if (!data) {
  38981. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38982. }
  38983. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38984. };
  38985. Geometry.prototype._applyToMesh = function (mesh) {
  38986. var numOfMeshes = this._meshes.length;
  38987. // vertexBuffers
  38988. for (var kind in this._vertexBuffers) {
  38989. if (numOfMeshes === 1) {
  38990. this._vertexBuffers[kind].create();
  38991. }
  38992. var buffer = this._vertexBuffers[kind].getBuffer();
  38993. if (buffer)
  38994. buffer.references = numOfMeshes;
  38995. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38996. if (!this._extend) {
  38997. this._updateExtend();
  38998. }
  38999. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39000. mesh._createGlobalSubMesh(false);
  39001. //bounding info was just created again, world matrix should be applied again.
  39002. mesh._updateBoundingInfo();
  39003. }
  39004. }
  39005. // indexBuffer
  39006. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39007. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39008. }
  39009. if (this._indexBuffer) {
  39010. this._indexBuffer.references = numOfMeshes;
  39011. }
  39012. };
  39013. Geometry.prototype.notifyUpdate = function (kind) {
  39014. if (this.onGeometryUpdated) {
  39015. this.onGeometryUpdated(this, kind);
  39016. }
  39017. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39018. var mesh = _a[_i];
  39019. mesh._markSubMeshesAsAttributesDirty();
  39020. }
  39021. };
  39022. /**
  39023. * Load the geometry if it was flagged as delay loaded
  39024. * @param scene defines the hosting scene
  39025. * @param onLoaded defines a callback called when the geometry is loaded
  39026. */
  39027. Geometry.prototype.load = function (scene, onLoaded) {
  39028. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39029. return;
  39030. }
  39031. if (this.isReady()) {
  39032. if (onLoaded) {
  39033. onLoaded();
  39034. }
  39035. return;
  39036. }
  39037. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39038. this._queueLoad(scene, onLoaded);
  39039. };
  39040. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39041. var _this = this;
  39042. if (!this.delayLoadingFile) {
  39043. return;
  39044. }
  39045. scene._addPendingData(this);
  39046. scene._loadFile(this.delayLoadingFile, function (data) {
  39047. if (!_this._delayLoadingFunction) {
  39048. return;
  39049. }
  39050. _this._delayLoadingFunction(JSON.parse(data), _this);
  39051. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39052. _this._delayInfo = [];
  39053. scene._removePendingData(_this);
  39054. var meshes = _this._meshes;
  39055. var numOfMeshes = meshes.length;
  39056. for (var index = 0; index < numOfMeshes; index++) {
  39057. _this._applyToMesh(meshes[index]);
  39058. }
  39059. if (onLoaded) {
  39060. onLoaded();
  39061. }
  39062. }, undefined, true);
  39063. };
  39064. /**
  39065. * Invert the geometry to move from a right handed system to a left handed one.
  39066. */
  39067. Geometry.prototype.toLeftHanded = function () {
  39068. // Flip faces
  39069. var tIndices = this.getIndices(false);
  39070. if (tIndices != null && tIndices.length > 0) {
  39071. for (var i = 0; i < tIndices.length; i += 3) {
  39072. var tTemp = tIndices[i + 0];
  39073. tIndices[i + 0] = tIndices[i + 2];
  39074. tIndices[i + 2] = tTemp;
  39075. }
  39076. this.setIndices(tIndices);
  39077. }
  39078. // Negate position.z
  39079. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39080. if (tPositions != null && tPositions.length > 0) {
  39081. for (var i = 0; i < tPositions.length; i += 3) {
  39082. tPositions[i + 2] = -tPositions[i + 2];
  39083. }
  39084. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39085. }
  39086. // Negate normal.z
  39087. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39088. if (tNormals != null && tNormals.length > 0) {
  39089. for (var i = 0; i < tNormals.length; i += 3) {
  39090. tNormals[i + 2] = -tNormals[i + 2];
  39091. }
  39092. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39093. }
  39094. };
  39095. // Cache
  39096. /** @hidden */
  39097. Geometry.prototype._resetPointsArrayCache = function () {
  39098. this._positions = null;
  39099. };
  39100. /** @hidden */
  39101. Geometry.prototype._generatePointsArray = function () {
  39102. if (this._positions)
  39103. return true;
  39104. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39105. if (!data || data.length === 0) {
  39106. return false;
  39107. }
  39108. this._positions = [];
  39109. for (var index = 0; index < data.length; index += 3) {
  39110. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39111. }
  39112. return true;
  39113. };
  39114. /**
  39115. * Gets a value indicating if the geometry is disposed
  39116. * @returns true if the geometry was disposed
  39117. */
  39118. Geometry.prototype.isDisposed = function () {
  39119. return this._isDisposed;
  39120. };
  39121. Geometry.prototype._disposeVertexArrayObjects = function () {
  39122. if (this._vertexArrayObjects) {
  39123. for (var kind in this._vertexArrayObjects) {
  39124. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39125. }
  39126. this._vertexArrayObjects = {};
  39127. }
  39128. };
  39129. /**
  39130. * Free all associated resources
  39131. */
  39132. Geometry.prototype.dispose = function () {
  39133. var meshes = this._meshes;
  39134. var numOfMeshes = meshes.length;
  39135. var index;
  39136. for (index = 0; index < numOfMeshes; index++) {
  39137. this.releaseForMesh(meshes[index]);
  39138. }
  39139. this._meshes = [];
  39140. this._disposeVertexArrayObjects();
  39141. for (var kind in this._vertexBuffers) {
  39142. this._vertexBuffers[kind].dispose();
  39143. }
  39144. this._vertexBuffers = {};
  39145. this._totalVertices = 0;
  39146. if (this._indexBuffer) {
  39147. this._engine._releaseBuffer(this._indexBuffer);
  39148. }
  39149. this._indexBuffer = null;
  39150. this._indices = [];
  39151. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39152. this.delayLoadingFile = null;
  39153. this._delayLoadingFunction = null;
  39154. this._delayInfo = [];
  39155. this._boundingInfo = null;
  39156. this._scene.removeGeometry(this);
  39157. this._isDisposed = true;
  39158. };
  39159. /**
  39160. * Clone the current geometry into a new geometry
  39161. * @param id defines the unique ID of the new geometry
  39162. * @returns a new geometry object
  39163. */
  39164. Geometry.prototype.copy = function (id) {
  39165. var vertexData = new BABYLON.VertexData();
  39166. vertexData.indices = [];
  39167. var indices = this.getIndices();
  39168. if (indices) {
  39169. for (var index = 0; index < indices.length; index++) {
  39170. vertexData.indices.push(indices[index]);
  39171. }
  39172. }
  39173. var updatable = false;
  39174. var stopChecking = false;
  39175. var kind;
  39176. for (kind in this._vertexBuffers) {
  39177. // using slice() to make a copy of the array and not just reference it
  39178. var data = this.getVerticesData(kind);
  39179. if (data instanceof Float32Array) {
  39180. vertexData.set(new Float32Array(data), kind);
  39181. }
  39182. else {
  39183. vertexData.set(data.slice(0), kind);
  39184. }
  39185. if (!stopChecking) {
  39186. var vb = this.getVertexBuffer(kind);
  39187. if (vb) {
  39188. updatable = vb.isUpdatable();
  39189. stopChecking = !updatable;
  39190. }
  39191. }
  39192. }
  39193. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39194. geometry.delayLoadState = this.delayLoadState;
  39195. geometry.delayLoadingFile = this.delayLoadingFile;
  39196. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39197. for (kind in this._delayInfo) {
  39198. geometry._delayInfo = geometry._delayInfo || [];
  39199. geometry._delayInfo.push(kind);
  39200. }
  39201. // Bounding info
  39202. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39203. return geometry;
  39204. };
  39205. /**
  39206. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39207. * @return a JSON representation of the current geometry data (without the vertices data)
  39208. */
  39209. Geometry.prototype.serialize = function () {
  39210. var serializationObject = {};
  39211. serializationObject.id = this.id;
  39212. serializationObject.updatable = this._updatable;
  39213. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39214. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39215. }
  39216. return serializationObject;
  39217. };
  39218. Geometry.prototype.toNumberArray = function (origin) {
  39219. if (Array.isArray(origin)) {
  39220. return origin;
  39221. }
  39222. else {
  39223. return Array.prototype.slice.call(origin);
  39224. }
  39225. };
  39226. /**
  39227. * Serialize all vertices data into a JSON oject
  39228. * @returns a JSON representation of the current geometry data
  39229. */
  39230. Geometry.prototype.serializeVerticeData = function () {
  39231. var serializationObject = this.serialize();
  39232. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39233. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39234. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39235. serializationObject.positions._updatable = true;
  39236. }
  39237. }
  39238. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39239. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39240. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39241. serializationObject.normals._updatable = true;
  39242. }
  39243. }
  39244. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39245. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39246. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39247. serializationObject.tangets._updatable = true;
  39248. }
  39249. }
  39250. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39251. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39252. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39253. serializationObject.uvs._updatable = true;
  39254. }
  39255. }
  39256. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39257. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39258. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39259. serializationObject.uv2s._updatable = true;
  39260. }
  39261. }
  39262. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39263. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39264. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39265. serializationObject.uv3s._updatable = true;
  39266. }
  39267. }
  39268. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39269. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39270. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39271. serializationObject.uv4s._updatable = true;
  39272. }
  39273. }
  39274. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39275. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39276. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39277. serializationObject.uv5s._updatable = true;
  39278. }
  39279. }
  39280. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39281. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39282. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39283. serializationObject.uv6s._updatable = true;
  39284. }
  39285. }
  39286. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39287. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39288. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39289. serializationObject.colors._updatable = true;
  39290. }
  39291. }
  39292. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39293. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39294. serializationObject.matricesIndices._isExpanded = true;
  39295. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39296. serializationObject.matricesIndices._updatable = true;
  39297. }
  39298. }
  39299. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39300. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39301. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39302. serializationObject.matricesWeights._updatable = true;
  39303. }
  39304. }
  39305. serializationObject.indices = this.toNumberArray(this.getIndices());
  39306. return serializationObject;
  39307. };
  39308. // Statics
  39309. /**
  39310. * Extracts a clone of a mesh geometry
  39311. * @param mesh defines the source mesh
  39312. * @param id defines the unique ID of the new geometry object
  39313. * @returns the new geometry object
  39314. */
  39315. Geometry.ExtractFromMesh = function (mesh, id) {
  39316. var geometry = mesh._geometry;
  39317. if (!geometry) {
  39318. return null;
  39319. }
  39320. return geometry.copy(id);
  39321. };
  39322. /**
  39323. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39324. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39325. * Be aware Math.random() could cause collisions, but:
  39326. * "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"
  39327. * @returns a string containing a new GUID
  39328. */
  39329. Geometry.RandomId = function () {
  39330. return BABYLON.Tools.RandomId();
  39331. };
  39332. /** @hidden */
  39333. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39334. var scene = mesh.getScene();
  39335. // Geometry
  39336. var geometryId = parsedGeometry.geometryId;
  39337. if (geometryId) {
  39338. var geometry = scene.getGeometryByID(geometryId);
  39339. if (geometry) {
  39340. geometry.applyToMesh(mesh);
  39341. }
  39342. }
  39343. else if (parsedGeometry instanceof ArrayBuffer) {
  39344. var binaryInfo = mesh._binaryInfo;
  39345. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39346. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39347. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39348. }
  39349. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39350. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39351. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39352. }
  39353. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39354. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39355. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39356. }
  39357. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39358. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39359. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39360. }
  39361. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39362. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39363. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39364. }
  39365. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39366. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39367. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39368. }
  39369. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39370. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39371. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39372. }
  39373. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39374. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39375. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39376. }
  39377. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39378. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39379. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39380. }
  39381. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39382. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39383. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39384. }
  39385. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39386. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39387. var floatIndices = [];
  39388. for (var i = 0; i < matricesIndicesData.length; i++) {
  39389. var index = matricesIndicesData[i];
  39390. floatIndices.push(index & 0x000000FF);
  39391. floatIndices.push((index & 0x0000FF00) >> 8);
  39392. floatIndices.push((index & 0x00FF0000) >> 16);
  39393. floatIndices.push(index >> 24);
  39394. }
  39395. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39396. }
  39397. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39398. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39399. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39400. }
  39401. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39402. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39403. mesh.setIndices(indicesData, null);
  39404. }
  39405. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39406. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39407. mesh.subMeshes = [];
  39408. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39409. var materialIndex = subMeshesData[(i * 5) + 0];
  39410. var verticesStart = subMeshesData[(i * 5) + 1];
  39411. var verticesCount = subMeshesData[(i * 5) + 2];
  39412. var indexStart = subMeshesData[(i * 5) + 3];
  39413. var indexCount = subMeshesData[(i * 5) + 4];
  39414. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39415. }
  39416. }
  39417. }
  39418. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39419. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39420. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39421. if (parsedGeometry.tangents) {
  39422. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39423. }
  39424. if (parsedGeometry.uvs) {
  39425. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39426. }
  39427. if (parsedGeometry.uvs2) {
  39428. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39429. }
  39430. if (parsedGeometry.uvs3) {
  39431. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39432. }
  39433. if (parsedGeometry.uvs4) {
  39434. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39435. }
  39436. if (parsedGeometry.uvs5) {
  39437. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39438. }
  39439. if (parsedGeometry.uvs6) {
  39440. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39441. }
  39442. if (parsedGeometry.colors) {
  39443. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39444. }
  39445. if (parsedGeometry.matricesIndices) {
  39446. if (!parsedGeometry.matricesIndices._isExpanded) {
  39447. var floatIndices = [];
  39448. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39449. var matricesIndex = parsedGeometry.matricesIndices[i];
  39450. floatIndices.push(matricesIndex & 0x000000FF);
  39451. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39452. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39453. floatIndices.push(matricesIndex >> 24);
  39454. }
  39455. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39456. }
  39457. else {
  39458. delete parsedGeometry.matricesIndices._isExpanded;
  39459. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39460. }
  39461. }
  39462. if (parsedGeometry.matricesIndicesExtra) {
  39463. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39464. var floatIndices = [];
  39465. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39466. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39467. floatIndices.push(matricesIndex & 0x000000FF);
  39468. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39469. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39470. floatIndices.push(matricesIndex >> 24);
  39471. }
  39472. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39473. }
  39474. else {
  39475. delete parsedGeometry.matricesIndices._isExpanded;
  39476. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39477. }
  39478. }
  39479. if (parsedGeometry.matricesWeights) {
  39480. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39481. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39482. }
  39483. if (parsedGeometry.matricesWeightsExtra) {
  39484. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39485. }
  39486. mesh.setIndices(parsedGeometry.indices, null);
  39487. }
  39488. // SubMeshes
  39489. if (parsedGeometry.subMeshes) {
  39490. mesh.subMeshes = [];
  39491. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39492. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39493. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39494. }
  39495. }
  39496. // Flat shading
  39497. if (mesh._shouldGenerateFlatShading) {
  39498. mesh.convertToFlatShadedMesh();
  39499. delete mesh._shouldGenerateFlatShading;
  39500. }
  39501. // Update
  39502. mesh.computeWorldMatrix(true);
  39503. // Octree
  39504. var sceneOctree = scene.selectionOctree;
  39505. if (sceneOctree !== undefined && sceneOctree !== null) {
  39506. sceneOctree.addMesh(mesh);
  39507. }
  39508. };
  39509. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39510. var epsilon = 1e-3;
  39511. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39512. return;
  39513. }
  39514. var noInfluenceBoneIndex = 0.0;
  39515. if (parsedGeometry.skeletonId > -1) {
  39516. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39517. if (!skeleton) {
  39518. return;
  39519. }
  39520. noInfluenceBoneIndex = skeleton.bones.length;
  39521. }
  39522. else {
  39523. return;
  39524. }
  39525. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39526. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39527. var matricesWeights = parsedGeometry.matricesWeights;
  39528. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39529. var influencers = parsedGeometry.numBoneInfluencer;
  39530. var size = matricesWeights.length;
  39531. for (var i = 0; i < size; i += 4) {
  39532. var weight = 0.0;
  39533. var firstZeroWeight = -1;
  39534. for (var j = 0; j < 4; j++) {
  39535. var w = matricesWeights[i + j];
  39536. weight += w;
  39537. if (w < epsilon && firstZeroWeight < 0) {
  39538. firstZeroWeight = j;
  39539. }
  39540. }
  39541. if (matricesWeightsExtra) {
  39542. for (var j = 0; j < 4; j++) {
  39543. var w = matricesWeightsExtra[i + j];
  39544. weight += w;
  39545. if (w < epsilon && firstZeroWeight < 0) {
  39546. firstZeroWeight = j + 4;
  39547. }
  39548. }
  39549. }
  39550. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39551. firstZeroWeight = influencers - 1;
  39552. }
  39553. if (weight > epsilon) {
  39554. var mweight = 1.0 / weight;
  39555. for (var j = 0; j < 4; j++) {
  39556. matricesWeights[i + j] *= mweight;
  39557. }
  39558. if (matricesWeightsExtra) {
  39559. for (var j = 0; j < 4; j++) {
  39560. matricesWeightsExtra[i + j] *= mweight;
  39561. }
  39562. }
  39563. }
  39564. else {
  39565. if (firstZeroWeight >= 4) {
  39566. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39567. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39568. }
  39569. else {
  39570. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39571. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39572. }
  39573. }
  39574. }
  39575. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39576. if (parsedGeometry.matricesWeightsExtra) {
  39577. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39578. }
  39579. };
  39580. /**
  39581. * Create a new geometry from persisted data (Using .babylon file format)
  39582. * @param parsedVertexData defines the persisted data
  39583. * @param scene defines the hosting scene
  39584. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39585. * @returns the new geometry object
  39586. */
  39587. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39588. if (scene.getGeometryByID(parsedVertexData.id)) {
  39589. return null; // null since geometry could be something else than a box...
  39590. }
  39591. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39592. if (BABYLON.Tags) {
  39593. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39594. }
  39595. if (parsedVertexData.delayLoadingFile) {
  39596. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39597. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39598. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39599. geometry._delayInfo = [];
  39600. if (parsedVertexData.hasUVs) {
  39601. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39602. }
  39603. if (parsedVertexData.hasUVs2) {
  39604. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39605. }
  39606. if (parsedVertexData.hasUVs3) {
  39607. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39608. }
  39609. if (parsedVertexData.hasUVs4) {
  39610. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39611. }
  39612. if (parsedVertexData.hasUVs5) {
  39613. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39614. }
  39615. if (parsedVertexData.hasUVs6) {
  39616. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39617. }
  39618. if (parsedVertexData.hasColors) {
  39619. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39620. }
  39621. if (parsedVertexData.hasMatricesIndices) {
  39622. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39623. }
  39624. if (parsedVertexData.hasMatricesWeights) {
  39625. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39626. }
  39627. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39628. }
  39629. else {
  39630. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39631. }
  39632. scene.pushGeometry(geometry, true);
  39633. return geometry;
  39634. };
  39635. return Geometry;
  39636. }());
  39637. BABYLON.Geometry = Geometry;
  39638. // Primitives
  39639. /// Abstract class
  39640. /**
  39641. * Abstract class used to provide common services for all typed geometries
  39642. * @hidden
  39643. */
  39644. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39645. __extends(_PrimitiveGeometry, _super);
  39646. /**
  39647. * Creates a new typed geometry
  39648. * @param id defines the unique ID of the geometry
  39649. * @param scene defines the hosting scene
  39650. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39651. * @param mesh defines the hosting mesh (can be null)
  39652. */
  39653. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39654. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39655. if (mesh === void 0) { mesh = null; }
  39656. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39657. _this._canBeRegenerated = _canBeRegenerated;
  39658. _this._beingRegenerated = true;
  39659. _this.regenerate();
  39660. _this._beingRegenerated = false;
  39661. return _this;
  39662. }
  39663. /**
  39664. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39665. * @returns true if the geometry can be regenerated
  39666. */
  39667. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39668. return this._canBeRegenerated;
  39669. };
  39670. /**
  39671. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39672. */
  39673. _PrimitiveGeometry.prototype.regenerate = function () {
  39674. if (!this._canBeRegenerated) {
  39675. return;
  39676. }
  39677. this._beingRegenerated = true;
  39678. this.setAllVerticesData(this._regenerateVertexData(), false);
  39679. this._beingRegenerated = false;
  39680. };
  39681. /**
  39682. * Clone the geometry
  39683. * @param id defines the unique ID of the new geometry
  39684. * @returns the new geometry
  39685. */
  39686. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39687. return _super.prototype.copy.call(this, id);
  39688. };
  39689. // overrides
  39690. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39691. if (!this._beingRegenerated) {
  39692. return;
  39693. }
  39694. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39695. };
  39696. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39697. if (!this._beingRegenerated) {
  39698. return;
  39699. }
  39700. _super.prototype.setVerticesData.call(this, kind, data, false);
  39701. };
  39702. // to override
  39703. /** @hidden */
  39704. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39705. throw new Error("Abstract method");
  39706. };
  39707. _PrimitiveGeometry.prototype.copy = function (id) {
  39708. throw new Error("Must be overriden in sub-classes.");
  39709. };
  39710. _PrimitiveGeometry.prototype.serialize = function () {
  39711. var serializationObject = _super.prototype.serialize.call(this);
  39712. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39713. return serializationObject;
  39714. };
  39715. return _PrimitiveGeometry;
  39716. }(Geometry));
  39717. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39718. /**
  39719. * Creates a ribbon geometry
  39720. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39721. */
  39722. var RibbonGeometry = /** @class */ (function (_super) {
  39723. __extends(RibbonGeometry, _super);
  39724. /**
  39725. * Creates a ribbon geometry
  39726. * @param id defines the unique ID of the geometry
  39727. * @param scene defines the hosting scene
  39728. * @param pathArray defines the array of paths to use
  39729. * @param closeArray defines if the last path and the first path must be joined
  39730. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39731. * @param offset defines the offset between points
  39732. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39733. * @param mesh defines the hosting mesh (can be null)
  39734. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39735. */
  39736. function RibbonGeometry(id, scene,
  39737. /**
  39738. * Defines the array of paths to use
  39739. */
  39740. pathArray,
  39741. /**
  39742. * Defines if the last and first points of each path in your pathArray must be joined
  39743. */
  39744. closeArray,
  39745. /**
  39746. * Defines if the last and first points of each path in your pathArray must be joined
  39747. */
  39748. closePath,
  39749. /**
  39750. * Defines the offset between points
  39751. */
  39752. offset, canBeRegenerated, mesh,
  39753. /**
  39754. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39755. */
  39756. side) {
  39757. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39758. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39759. _this.pathArray = pathArray;
  39760. _this.closeArray = closeArray;
  39761. _this.closePath = closePath;
  39762. _this.offset = offset;
  39763. _this.side = side;
  39764. return _this;
  39765. }
  39766. /** @hidden */
  39767. RibbonGeometry.prototype._regenerateVertexData = function () {
  39768. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39769. };
  39770. RibbonGeometry.prototype.copy = function (id) {
  39771. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39772. };
  39773. return RibbonGeometry;
  39774. }(_PrimitiveGeometry));
  39775. BABYLON.RibbonGeometry = RibbonGeometry;
  39776. /**
  39777. * Creates a box geometry
  39778. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39779. */
  39780. var BoxGeometry = /** @class */ (function (_super) {
  39781. __extends(BoxGeometry, _super);
  39782. /**
  39783. * Creates a box geometry
  39784. * @param id defines the unique ID of the geometry
  39785. * @param scene defines the hosting scene
  39786. * @param size defines the zise of the box (width, height and depth are the same)
  39787. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39788. * @param mesh defines the hosting mesh (can be null)
  39789. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39790. */
  39791. function BoxGeometry(id, scene,
  39792. /**
  39793. * Defines the zise of the box (width, height and depth are the same)
  39794. */
  39795. size, canBeRegenerated, mesh,
  39796. /**
  39797. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39798. */
  39799. side) {
  39800. if (mesh === void 0) { mesh = null; }
  39801. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39802. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39803. _this.size = size;
  39804. _this.side = side;
  39805. return _this;
  39806. }
  39807. BoxGeometry.prototype._regenerateVertexData = function () {
  39808. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39809. };
  39810. BoxGeometry.prototype.copy = function (id) {
  39811. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39812. };
  39813. BoxGeometry.prototype.serialize = function () {
  39814. var serializationObject = _super.prototype.serialize.call(this);
  39815. serializationObject.size = this.size;
  39816. return serializationObject;
  39817. };
  39818. BoxGeometry.Parse = function (parsedBox, scene) {
  39819. if (scene.getGeometryByID(parsedBox.id)) {
  39820. return null; // null since geometry could be something else than a box...
  39821. }
  39822. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39823. if (BABYLON.Tags) {
  39824. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39825. }
  39826. scene.pushGeometry(box, true);
  39827. return box;
  39828. };
  39829. return BoxGeometry;
  39830. }(_PrimitiveGeometry));
  39831. BABYLON.BoxGeometry = BoxGeometry;
  39832. /**
  39833. * Creates a sphere geometry
  39834. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39835. */
  39836. var SphereGeometry = /** @class */ (function (_super) {
  39837. __extends(SphereGeometry, _super);
  39838. /**
  39839. * Create a new sphere geometry
  39840. * @param id defines the unique ID of the geometry
  39841. * @param scene defines the hosting scene
  39842. * @param segments defines the number of segments to use to create the sphere
  39843. * @param diameter defines the diameter of the sphere
  39844. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39845. * @param mesh defines the hosting mesh (can be null)
  39846. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39847. */
  39848. function SphereGeometry(id, scene,
  39849. /**
  39850. * Defines the number of segments to use to create the sphere
  39851. */
  39852. segments,
  39853. /**
  39854. * Defines the diameter of the sphere
  39855. */
  39856. diameter, canBeRegenerated, mesh,
  39857. /**
  39858. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39859. */
  39860. side) {
  39861. if (mesh === void 0) { mesh = null; }
  39862. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39863. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39864. _this.segments = segments;
  39865. _this.diameter = diameter;
  39866. _this.side = side;
  39867. return _this;
  39868. }
  39869. SphereGeometry.prototype._regenerateVertexData = function () {
  39870. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39871. };
  39872. SphereGeometry.prototype.copy = function (id) {
  39873. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39874. };
  39875. SphereGeometry.prototype.serialize = function () {
  39876. var serializationObject = _super.prototype.serialize.call(this);
  39877. serializationObject.segments = this.segments;
  39878. serializationObject.diameter = this.diameter;
  39879. return serializationObject;
  39880. };
  39881. SphereGeometry.Parse = function (parsedSphere, scene) {
  39882. if (scene.getGeometryByID(parsedSphere.id)) {
  39883. return null; // null since geometry could be something else than a sphere...
  39884. }
  39885. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39886. if (BABYLON.Tags) {
  39887. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39888. }
  39889. scene.pushGeometry(sphere, true);
  39890. return sphere;
  39891. };
  39892. return SphereGeometry;
  39893. }(_PrimitiveGeometry));
  39894. BABYLON.SphereGeometry = SphereGeometry;
  39895. /**
  39896. * Creates a disc geometry
  39897. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39898. */
  39899. var DiscGeometry = /** @class */ (function (_super) {
  39900. __extends(DiscGeometry, _super);
  39901. /**
  39902. * Creates a new disc geometry
  39903. * @param id defines the unique ID of the geometry
  39904. * @param scene defines the hosting scene
  39905. * @param radius defines the radius of the disc
  39906. * @param tessellation defines the tesselation factor to apply to the disc
  39907. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39908. * @param mesh defines the hosting mesh (can be null)
  39909. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39910. */
  39911. function DiscGeometry(id, scene,
  39912. /**
  39913. * Defines the radius of the disc
  39914. */
  39915. radius,
  39916. /**
  39917. * Defines the tesselation factor to apply to the disc
  39918. */
  39919. tessellation, canBeRegenerated, mesh,
  39920. /**
  39921. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39922. */
  39923. side) {
  39924. if (mesh === void 0) { mesh = null; }
  39925. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39926. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39927. _this.radius = radius;
  39928. _this.tessellation = tessellation;
  39929. _this.side = side;
  39930. return _this;
  39931. }
  39932. DiscGeometry.prototype._regenerateVertexData = function () {
  39933. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39934. };
  39935. DiscGeometry.prototype.copy = function (id) {
  39936. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39937. };
  39938. return DiscGeometry;
  39939. }(_PrimitiveGeometry));
  39940. BABYLON.DiscGeometry = DiscGeometry;
  39941. /**
  39942. * Creates a new cylinder geometry
  39943. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39944. */
  39945. var CylinderGeometry = /** @class */ (function (_super) {
  39946. __extends(CylinderGeometry, _super);
  39947. /**
  39948. * Creates a new cylinder geometry
  39949. * @param id defines the unique ID of the geometry
  39950. * @param scene defines the hosting scene
  39951. * @param height defines the height of the cylinder
  39952. * @param diameterTop defines the diameter of the cylinder's top cap
  39953. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39954. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39955. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39956. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39957. * @param mesh defines the hosting mesh (can be null)
  39958. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39959. */
  39960. function CylinderGeometry(id, scene,
  39961. /**
  39962. * Defines the height of the cylinder
  39963. */
  39964. height,
  39965. /**
  39966. * Defines the diameter of the cylinder's top cap
  39967. */
  39968. diameterTop,
  39969. /**
  39970. * Defines the diameter of the cylinder's bottom cap
  39971. */
  39972. diameterBottom,
  39973. /**
  39974. * Defines the tessellation factor to apply to the cylinder
  39975. */
  39976. tessellation,
  39977. /**
  39978. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39979. */
  39980. subdivisions, canBeRegenerated, mesh,
  39981. /**
  39982. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39983. */
  39984. side) {
  39985. if (subdivisions === void 0) { subdivisions = 1; }
  39986. if (mesh === void 0) { mesh = null; }
  39987. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39988. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39989. _this.height = height;
  39990. _this.diameterTop = diameterTop;
  39991. _this.diameterBottom = diameterBottom;
  39992. _this.tessellation = tessellation;
  39993. _this.subdivisions = subdivisions;
  39994. _this.side = side;
  39995. return _this;
  39996. }
  39997. CylinderGeometry.prototype._regenerateVertexData = function () {
  39998. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39999. };
  40000. CylinderGeometry.prototype.copy = function (id) {
  40001. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40002. };
  40003. CylinderGeometry.prototype.serialize = function () {
  40004. var serializationObject = _super.prototype.serialize.call(this);
  40005. serializationObject.height = this.height;
  40006. serializationObject.diameterTop = this.diameterTop;
  40007. serializationObject.diameterBottom = this.diameterBottom;
  40008. serializationObject.tessellation = this.tessellation;
  40009. return serializationObject;
  40010. };
  40011. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40012. if (scene.getGeometryByID(parsedCylinder.id)) {
  40013. return null; // null since geometry could be something else than a cylinder...
  40014. }
  40015. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40016. if (BABYLON.Tags) {
  40017. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40018. }
  40019. scene.pushGeometry(cylinder, true);
  40020. return cylinder;
  40021. };
  40022. return CylinderGeometry;
  40023. }(_PrimitiveGeometry));
  40024. BABYLON.CylinderGeometry = CylinderGeometry;
  40025. /**
  40026. * Creates a new torus geometry
  40027. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40028. */
  40029. var TorusGeometry = /** @class */ (function (_super) {
  40030. __extends(TorusGeometry, _super);
  40031. /**
  40032. * Creates a new torus geometry
  40033. * @param id defines the unique ID of the geometry
  40034. * @param scene defines the hosting scene
  40035. * @param diameter defines the diameter of the torus
  40036. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40037. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40038. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40039. * @param mesh defines the hosting mesh (can be null)
  40040. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40041. */
  40042. function TorusGeometry(id, scene,
  40043. /**
  40044. * Defines the diameter of the torus
  40045. */
  40046. diameter,
  40047. /**
  40048. * Defines the thickness of the torus (ie. internal diameter)
  40049. */
  40050. thickness,
  40051. /**
  40052. * Defines the tesselation factor to apply to the torus
  40053. */
  40054. tessellation, canBeRegenerated, mesh,
  40055. /**
  40056. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40057. */
  40058. side) {
  40059. if (mesh === void 0) { mesh = null; }
  40060. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40061. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40062. _this.diameter = diameter;
  40063. _this.thickness = thickness;
  40064. _this.tessellation = tessellation;
  40065. _this.side = side;
  40066. return _this;
  40067. }
  40068. TorusGeometry.prototype._regenerateVertexData = function () {
  40069. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40070. };
  40071. TorusGeometry.prototype.copy = function (id) {
  40072. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40073. };
  40074. TorusGeometry.prototype.serialize = function () {
  40075. var serializationObject = _super.prototype.serialize.call(this);
  40076. serializationObject.diameter = this.diameter;
  40077. serializationObject.thickness = this.thickness;
  40078. serializationObject.tessellation = this.tessellation;
  40079. return serializationObject;
  40080. };
  40081. TorusGeometry.Parse = function (parsedTorus, scene) {
  40082. if (scene.getGeometryByID(parsedTorus.id)) {
  40083. return null; // null since geometry could be something else than a torus...
  40084. }
  40085. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40086. if (BABYLON.Tags) {
  40087. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40088. }
  40089. scene.pushGeometry(torus, true);
  40090. return torus;
  40091. };
  40092. return TorusGeometry;
  40093. }(_PrimitiveGeometry));
  40094. BABYLON.TorusGeometry = TorusGeometry;
  40095. /**
  40096. * Creates a new ground geometry
  40097. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40098. */
  40099. var GroundGeometry = /** @class */ (function (_super) {
  40100. __extends(GroundGeometry, _super);
  40101. /**
  40102. * Creates a new ground geometry
  40103. * @param id defines the unique ID of the geometry
  40104. * @param scene defines the hosting scene
  40105. * @param width defines the width of the ground
  40106. * @param height defines the height of the ground
  40107. * @param subdivisions defines the subdivisions to apply to the ground
  40108. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40109. * @param mesh defines the hosting mesh (can be null)
  40110. */
  40111. function GroundGeometry(id, scene,
  40112. /**
  40113. * Defines the width of the ground
  40114. */
  40115. width,
  40116. /**
  40117. * Defines the height of the ground
  40118. */
  40119. height,
  40120. /**
  40121. * Defines the subdivisions to apply to the ground
  40122. */
  40123. subdivisions, canBeRegenerated, mesh) {
  40124. if (mesh === void 0) { mesh = null; }
  40125. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40126. _this.width = width;
  40127. _this.height = height;
  40128. _this.subdivisions = subdivisions;
  40129. return _this;
  40130. }
  40131. GroundGeometry.prototype._regenerateVertexData = function () {
  40132. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40133. };
  40134. GroundGeometry.prototype.copy = function (id) {
  40135. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40136. };
  40137. GroundGeometry.prototype.serialize = function () {
  40138. var serializationObject = _super.prototype.serialize.call(this);
  40139. serializationObject.width = this.width;
  40140. serializationObject.height = this.height;
  40141. serializationObject.subdivisions = this.subdivisions;
  40142. return serializationObject;
  40143. };
  40144. GroundGeometry.Parse = function (parsedGround, scene) {
  40145. if (scene.getGeometryByID(parsedGround.id)) {
  40146. return null; // null since geometry could be something else than a ground...
  40147. }
  40148. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40149. if (BABYLON.Tags) {
  40150. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40151. }
  40152. scene.pushGeometry(ground, true);
  40153. return ground;
  40154. };
  40155. return GroundGeometry;
  40156. }(_PrimitiveGeometry));
  40157. BABYLON.GroundGeometry = GroundGeometry;
  40158. /**
  40159. * Creates a tiled ground geometry
  40160. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40161. */
  40162. var TiledGroundGeometry = /** @class */ (function (_super) {
  40163. __extends(TiledGroundGeometry, _super);
  40164. /**
  40165. * Creates a tiled ground geometry
  40166. * @param id defines the unique ID of the geometry
  40167. * @param scene defines the hosting scene
  40168. * @param xmin defines the minimum value on X axis
  40169. * @param zmin defines the minimum value on Z axis
  40170. * @param xmax defines the maximum value on X axis
  40171. * @param zmax defines the maximum value on Z axis
  40172. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40173. * @param precision defines the precision to use when computing the tiles
  40174. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40175. * @param mesh defines the hosting mesh (can be null)
  40176. */
  40177. function TiledGroundGeometry(id, scene,
  40178. /**
  40179. * Defines the minimum value on X axis
  40180. */
  40181. xmin,
  40182. /**
  40183. * Defines the minimum value on Z axis
  40184. */
  40185. zmin,
  40186. /**
  40187. * Defines the maximum value on X axis
  40188. */
  40189. xmax,
  40190. /**
  40191. * Defines the maximum value on Z axis
  40192. */
  40193. zmax,
  40194. /**
  40195. * Defines the subdivisions to apply to the ground
  40196. */
  40197. subdivisions,
  40198. /**
  40199. * Defines the precision to use when computing the tiles
  40200. */
  40201. precision, canBeRegenerated, mesh) {
  40202. if (mesh === void 0) { mesh = null; }
  40203. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40204. _this.xmin = xmin;
  40205. _this.zmin = zmin;
  40206. _this.xmax = xmax;
  40207. _this.zmax = zmax;
  40208. _this.subdivisions = subdivisions;
  40209. _this.precision = precision;
  40210. return _this;
  40211. }
  40212. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40213. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40214. };
  40215. TiledGroundGeometry.prototype.copy = function (id) {
  40216. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40217. };
  40218. return TiledGroundGeometry;
  40219. }(_PrimitiveGeometry));
  40220. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40221. /**
  40222. * Creates a plane geometry
  40223. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40224. */
  40225. var PlaneGeometry = /** @class */ (function (_super) {
  40226. __extends(PlaneGeometry, _super);
  40227. /**
  40228. * Creates a plane geometry
  40229. * @param id defines the unique ID of the geometry
  40230. * @param scene defines the hosting scene
  40231. * @param size defines the size of the plane (width === height)
  40232. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40233. * @param mesh defines the hosting mesh (can be null)
  40234. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40235. */
  40236. function PlaneGeometry(id, scene,
  40237. /**
  40238. * Defines the size of the plane (width === height)
  40239. */
  40240. size, canBeRegenerated, mesh,
  40241. /**
  40242. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40243. */
  40244. side) {
  40245. if (mesh === void 0) { mesh = null; }
  40246. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40247. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40248. _this.size = size;
  40249. _this.side = side;
  40250. return _this;
  40251. }
  40252. PlaneGeometry.prototype._regenerateVertexData = function () {
  40253. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40254. };
  40255. PlaneGeometry.prototype.copy = function (id) {
  40256. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40257. };
  40258. PlaneGeometry.prototype.serialize = function () {
  40259. var serializationObject = _super.prototype.serialize.call(this);
  40260. serializationObject.size = this.size;
  40261. return serializationObject;
  40262. };
  40263. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40264. if (scene.getGeometryByID(parsedPlane.id)) {
  40265. return null; // null since geometry could be something else than a ground...
  40266. }
  40267. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40268. if (BABYLON.Tags) {
  40269. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40270. }
  40271. scene.pushGeometry(plane, true);
  40272. return plane;
  40273. };
  40274. return PlaneGeometry;
  40275. }(_PrimitiveGeometry));
  40276. BABYLON.PlaneGeometry = PlaneGeometry;
  40277. /**
  40278. * Creates a torus knot geometry
  40279. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40280. */
  40281. var TorusKnotGeometry = /** @class */ (function (_super) {
  40282. __extends(TorusKnotGeometry, _super);
  40283. /**
  40284. * Creates a torus knot geometry
  40285. * @param id defines the unique ID of the geometry
  40286. * @param scene defines the hosting scene
  40287. * @param radius defines the radius of the torus knot
  40288. * @param tube defines the thickness of the torus knot tube
  40289. * @param radialSegments defines the number of radial segments
  40290. * @param tubularSegments defines the number of tubular segments
  40291. * @param p defines the first number of windings
  40292. * @param q defines the second number of windings
  40293. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40294. * @param mesh defines the hosting mesh (can be null)
  40295. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40296. */
  40297. function TorusKnotGeometry(id, scene,
  40298. /**
  40299. * Defines the radius of the torus knot
  40300. */
  40301. radius,
  40302. /**
  40303. * Defines the thickness of the torus knot tube
  40304. */
  40305. tube,
  40306. /**
  40307. * Defines the number of radial segments
  40308. */
  40309. radialSegments,
  40310. /**
  40311. * Defines the number of tubular segments
  40312. */
  40313. tubularSegments,
  40314. /**
  40315. * Defines the first number of windings
  40316. */
  40317. p,
  40318. /**
  40319. * Defines the second number of windings
  40320. */
  40321. q, canBeRegenerated, mesh,
  40322. /**
  40323. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40324. */
  40325. side) {
  40326. if (mesh === void 0) { mesh = null; }
  40327. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40328. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40329. _this.radius = radius;
  40330. _this.tube = tube;
  40331. _this.radialSegments = radialSegments;
  40332. _this.tubularSegments = tubularSegments;
  40333. _this.p = p;
  40334. _this.q = q;
  40335. _this.side = side;
  40336. return _this;
  40337. }
  40338. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40339. 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 });
  40340. };
  40341. TorusKnotGeometry.prototype.copy = function (id) {
  40342. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40343. };
  40344. TorusKnotGeometry.prototype.serialize = function () {
  40345. var serializationObject = _super.prototype.serialize.call(this);
  40346. serializationObject.radius = this.radius;
  40347. serializationObject.tube = this.tube;
  40348. serializationObject.radialSegments = this.radialSegments;
  40349. serializationObject.tubularSegments = this.tubularSegments;
  40350. serializationObject.p = this.p;
  40351. serializationObject.q = this.q;
  40352. return serializationObject;
  40353. };
  40354. ;
  40355. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40356. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40357. return null; // null since geometry could be something else than a ground...
  40358. }
  40359. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40360. if (BABYLON.Tags) {
  40361. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40362. }
  40363. scene.pushGeometry(torusKnot, true);
  40364. return torusKnot;
  40365. };
  40366. return TorusKnotGeometry;
  40367. }(_PrimitiveGeometry));
  40368. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40369. //}
  40370. })(BABYLON || (BABYLON = {}));
  40371. //# sourceMappingURL=babylon.geometry.js.map
  40372. var BABYLON;
  40373. (function (BABYLON) {
  40374. /**
  40375. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40376. */
  40377. var PerformanceMonitor = /** @class */ (function () {
  40378. /**
  40379. * constructor
  40380. * @param frameSampleSize The number of samples required to saturate the sliding window
  40381. */
  40382. function PerformanceMonitor(frameSampleSize) {
  40383. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40384. this._enabled = true;
  40385. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40386. }
  40387. /**
  40388. * Samples current frame
  40389. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40390. */
  40391. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40392. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40393. if (!this._enabled)
  40394. return;
  40395. if (this._lastFrameTimeMs != null) {
  40396. var dt = timeMs - this._lastFrameTimeMs;
  40397. this._rollingFrameTime.add(dt);
  40398. }
  40399. this._lastFrameTimeMs = timeMs;
  40400. };
  40401. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40402. /**
  40403. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40404. * @return Average frame time in milliseconds
  40405. */
  40406. get: function () {
  40407. return this._rollingFrameTime.average;
  40408. },
  40409. enumerable: true,
  40410. configurable: true
  40411. });
  40412. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40413. /**
  40414. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40415. * @return Frame time variance in milliseconds squared
  40416. */
  40417. get: function () {
  40418. return this._rollingFrameTime.variance;
  40419. },
  40420. enumerable: true,
  40421. configurable: true
  40422. });
  40423. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40424. /**
  40425. * Returns the frame time of the most recent frame
  40426. * @return Frame time in milliseconds
  40427. */
  40428. get: function () {
  40429. return this._rollingFrameTime.history(0);
  40430. },
  40431. enumerable: true,
  40432. configurable: true
  40433. });
  40434. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40435. /**
  40436. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40437. * @return Framerate in frames per second
  40438. */
  40439. get: function () {
  40440. return 1000.0 / this._rollingFrameTime.average;
  40441. },
  40442. enumerable: true,
  40443. configurable: true
  40444. });
  40445. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40446. /**
  40447. * Returns the average framerate in frames per second using the most recent frame time
  40448. * @return Framerate in frames per second
  40449. */
  40450. get: function () {
  40451. var history = this._rollingFrameTime.history(0);
  40452. if (history === 0) {
  40453. return 0;
  40454. }
  40455. return 1000.0 / history;
  40456. },
  40457. enumerable: true,
  40458. configurable: true
  40459. });
  40460. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40461. /**
  40462. * Returns true if enough samples have been taken to completely fill the sliding window
  40463. * @return true if saturated
  40464. */
  40465. get: function () {
  40466. return this._rollingFrameTime.isSaturated();
  40467. },
  40468. enumerable: true,
  40469. configurable: true
  40470. });
  40471. /**
  40472. * Enables contributions to the sliding window sample set
  40473. */
  40474. PerformanceMonitor.prototype.enable = function () {
  40475. this._enabled = true;
  40476. };
  40477. /**
  40478. * Disables contributions to the sliding window sample set
  40479. * Samples will not be interpolated over the disabled period
  40480. */
  40481. PerformanceMonitor.prototype.disable = function () {
  40482. this._enabled = false;
  40483. //clear last sample to avoid interpolating over the disabled period when next enabled
  40484. this._lastFrameTimeMs = null;
  40485. };
  40486. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40487. /**
  40488. * Returns true if sampling is enabled
  40489. * @return true if enabled
  40490. */
  40491. get: function () {
  40492. return this._enabled;
  40493. },
  40494. enumerable: true,
  40495. configurable: true
  40496. });
  40497. /**
  40498. * Resets performance monitor
  40499. */
  40500. PerformanceMonitor.prototype.reset = function () {
  40501. //clear last sample to avoid interpolating over the disabled period when next enabled
  40502. this._lastFrameTimeMs = null;
  40503. //wipe record
  40504. this._rollingFrameTime.reset();
  40505. };
  40506. return PerformanceMonitor;
  40507. }());
  40508. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40509. /**
  40510. * RollingAverage
  40511. *
  40512. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40513. */
  40514. var RollingAverage = /** @class */ (function () {
  40515. /**
  40516. * constructor
  40517. * @param length The number of samples required to saturate the sliding window
  40518. */
  40519. function RollingAverage(length) {
  40520. this._samples = new Array(length);
  40521. this.reset();
  40522. }
  40523. /**
  40524. * Adds a sample to the sample set
  40525. * @param v The sample value
  40526. */
  40527. RollingAverage.prototype.add = function (v) {
  40528. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40529. var delta;
  40530. //we need to check if we've already wrapped round
  40531. if (this.isSaturated()) {
  40532. //remove bottom of stack from mean
  40533. var bottomValue = this._samples[this._pos];
  40534. delta = bottomValue - this.average;
  40535. this.average -= delta / (this._sampleCount - 1);
  40536. this._m2 -= delta * (bottomValue - this.average);
  40537. }
  40538. else {
  40539. this._sampleCount++;
  40540. }
  40541. //add new value to mean
  40542. delta = v - this.average;
  40543. this.average += delta / (this._sampleCount);
  40544. this._m2 += delta * (v - this.average);
  40545. //set the new variance
  40546. this.variance = this._m2 / (this._sampleCount - 1);
  40547. this._samples[this._pos] = v;
  40548. this._pos++;
  40549. this._pos %= this._samples.length; //positive wrap around
  40550. };
  40551. /**
  40552. * Returns previously added values or null if outside of history or outside the sliding window domain
  40553. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40554. * @return Value previously recorded with add() or null if outside of range
  40555. */
  40556. RollingAverage.prototype.history = function (i) {
  40557. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40558. return 0;
  40559. }
  40560. var i0 = this._wrapPosition(this._pos - 1.0);
  40561. return this._samples[this._wrapPosition(i0 - i)];
  40562. };
  40563. /**
  40564. * Returns true if enough samples have been taken to completely fill the sliding window
  40565. * @return true if sample-set saturated
  40566. */
  40567. RollingAverage.prototype.isSaturated = function () {
  40568. return this._sampleCount >= this._samples.length;
  40569. };
  40570. /**
  40571. * Resets the rolling average (equivalent to 0 samples taken so far)
  40572. */
  40573. RollingAverage.prototype.reset = function () {
  40574. this.average = 0;
  40575. this.variance = 0;
  40576. this._sampleCount = 0;
  40577. this._pos = 0;
  40578. this._m2 = 0;
  40579. };
  40580. /**
  40581. * Wraps a value around the sample range boundaries
  40582. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40583. * @return Wrapped position in sample range
  40584. */
  40585. RollingAverage.prototype._wrapPosition = function (i) {
  40586. var max = this._samples.length;
  40587. return ((i % max) + max) % max;
  40588. };
  40589. return RollingAverage;
  40590. }());
  40591. BABYLON.RollingAverage = RollingAverage;
  40592. })(BABYLON || (BABYLON = {}));
  40593. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40594. var BABYLON;
  40595. (function (BABYLON) {
  40596. /**
  40597. * "Static Class" containing the most commonly used helper while dealing with material for
  40598. * rendering purpose.
  40599. *
  40600. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40601. *
  40602. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40603. */
  40604. var MaterialHelper = /** @class */ (function () {
  40605. function MaterialHelper() {
  40606. }
  40607. /**
  40608. * Bind the current view position to an effect.
  40609. * @param effect The effect to be bound
  40610. * @param scene The scene the eyes position is used from
  40611. */
  40612. MaterialHelper.BindEyePosition = function (effect, scene) {
  40613. if (scene._forcedViewPosition) {
  40614. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40615. return;
  40616. }
  40617. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40618. };
  40619. /**
  40620. * Helps preparing the defines values about the UVs in used in the effect.
  40621. * UVs are shared as much as we can accross chanels in the shaders.
  40622. * @param texture The texture we are preparing the UVs for
  40623. * @param defines The defines to update
  40624. * @param key The chanel key "diffuse", "specular"... used in the shader
  40625. */
  40626. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40627. defines._needUVs = true;
  40628. defines[key] = true;
  40629. if (texture.getTextureMatrix().isIdentity(true)) {
  40630. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40631. if (texture.coordinatesIndex === 0) {
  40632. defines["MAINUV1"] = true;
  40633. }
  40634. else {
  40635. defines["MAINUV2"] = true;
  40636. }
  40637. }
  40638. else {
  40639. defines[key + "DIRECTUV"] = 0;
  40640. }
  40641. };
  40642. /**
  40643. * Binds a texture matrix value to its corrsponding uniform
  40644. * @param texture The texture to bind the matrix for
  40645. * @param uniformBuffer The uniform buffer receivin the data
  40646. * @param key The chanel key "diffuse", "specular"... used in the shader
  40647. */
  40648. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40649. var matrix = texture.getTextureMatrix();
  40650. if (!matrix.isIdentity(true)) {
  40651. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40652. }
  40653. };
  40654. /**
  40655. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40656. * @param mesh defines the current mesh
  40657. * @param scene defines the current scene
  40658. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40659. * @param pointsCloud defines if point cloud rendering has to be turned on
  40660. * @param fogEnabled defines if fog has to be turned on
  40661. * @param alphaTest defines if alpha testing has to be turned on
  40662. * @param defines defines the current list of defines
  40663. */
  40664. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40665. if (defines._areMiscDirty) {
  40666. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40667. defines["POINTSIZE"] = pointsCloud;
  40668. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40669. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40670. defines["ALPHATEST"] = alphaTest;
  40671. }
  40672. };
  40673. /**
  40674. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40675. * @param scene defines the current scene
  40676. * @param engine defines the current engine
  40677. * @param defines specifies the list of active defines
  40678. * @param useInstances defines if instances have to be turned on
  40679. * @param useClipPlane defines if clip plane have to be turned on
  40680. */
  40681. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40682. if (useClipPlane === void 0) { useClipPlane = null; }
  40683. var changed = false;
  40684. if (useClipPlane == null) {
  40685. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40686. }
  40687. if (defines["CLIPPLANE"] !== useClipPlane) {
  40688. defines["CLIPPLANE"] = useClipPlane;
  40689. changed = true;
  40690. }
  40691. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40692. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40693. changed = true;
  40694. }
  40695. if (defines["INSTANCES"] !== useInstances) {
  40696. defines["INSTANCES"] = useInstances;
  40697. changed = true;
  40698. }
  40699. if (changed) {
  40700. defines.markAsUnprocessed();
  40701. }
  40702. };
  40703. /**
  40704. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40705. * @param mesh The mesh containing the geometry data we will draw
  40706. * @param defines The defines to update
  40707. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40708. * @param useBones Precise whether bones should be used or not (override mesh info)
  40709. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40710. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40711. * @returns false if defines are considered not dirty and have not been checked
  40712. */
  40713. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40714. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40715. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40716. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40717. return false;
  40718. }
  40719. defines._normals = defines._needNormals;
  40720. defines._uvs = defines._needUVs;
  40721. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40722. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40723. defines["TANGENT"] = true;
  40724. }
  40725. if (defines._needUVs) {
  40726. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40727. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40728. }
  40729. else {
  40730. defines["UV1"] = false;
  40731. defines["UV2"] = false;
  40732. }
  40733. if (useVertexColor) {
  40734. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40735. defines["VERTEXCOLOR"] = hasVertexColors;
  40736. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40737. }
  40738. if (useBones) {
  40739. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40740. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40741. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40742. }
  40743. else {
  40744. defines["NUM_BONE_INFLUENCERS"] = 0;
  40745. defines["BonesPerMesh"] = 0;
  40746. }
  40747. }
  40748. if (useMorphTargets) {
  40749. var manager = mesh.morphTargetManager;
  40750. if (manager) {
  40751. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40752. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40753. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40754. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40755. }
  40756. else {
  40757. defines["MORPHTARGETS_TANGENT"] = false;
  40758. defines["MORPHTARGETS_NORMAL"] = false;
  40759. defines["MORPHTARGETS"] = false;
  40760. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40761. }
  40762. }
  40763. return true;
  40764. };
  40765. /**
  40766. * Prepares the defines related to the light information passed in parameter
  40767. * @param scene The scene we are intending to draw
  40768. * @param mesh The mesh the effect is compiling for
  40769. * @param defines The defines to update
  40770. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40771. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40772. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40773. * @returns true if normals will be required for the rest of the effect
  40774. */
  40775. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40776. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40777. if (disableLighting === void 0) { disableLighting = false; }
  40778. if (!defines._areLightsDirty) {
  40779. return defines._needNormals;
  40780. }
  40781. var lightIndex = 0;
  40782. var needNormals = false;
  40783. var needRebuild = false;
  40784. var lightmapMode = false;
  40785. var shadowEnabled = false;
  40786. var specularEnabled = false;
  40787. if (scene.lightsEnabled && !disableLighting) {
  40788. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40789. var light = _a[_i];
  40790. needNormals = true;
  40791. if (defines["LIGHT" + lightIndex] === undefined) {
  40792. needRebuild = true;
  40793. }
  40794. defines["LIGHT" + lightIndex] = true;
  40795. defines["SPOTLIGHT" + lightIndex] = false;
  40796. defines["HEMILIGHT" + lightIndex] = false;
  40797. defines["POINTLIGHT" + lightIndex] = false;
  40798. defines["DIRLIGHT" + lightIndex] = false;
  40799. light.prepareLightSpecificDefines(defines, lightIndex);
  40800. // Specular
  40801. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40802. specularEnabled = true;
  40803. }
  40804. // Shadows
  40805. defines["SHADOW" + lightIndex] = false;
  40806. defines["SHADOWPCF" + lightIndex] = false;
  40807. defines["SHADOWPCSS" + lightIndex] = false;
  40808. defines["SHADOWPOISSON" + lightIndex] = false;
  40809. defines["SHADOWESM" + lightIndex] = false;
  40810. defines["SHADOWCUBE" + lightIndex] = false;
  40811. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40812. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40813. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40814. var shadowGenerator = light.getShadowGenerator();
  40815. if (shadowGenerator) {
  40816. var shadowMap = shadowGenerator.getShadowMap();
  40817. if (shadowMap) {
  40818. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40819. shadowEnabled = true;
  40820. shadowGenerator.prepareDefines(defines, lightIndex);
  40821. }
  40822. }
  40823. }
  40824. }
  40825. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40826. lightmapMode = true;
  40827. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40828. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40829. }
  40830. else {
  40831. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40832. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40833. }
  40834. lightIndex++;
  40835. if (lightIndex === maxSimultaneousLights)
  40836. break;
  40837. }
  40838. }
  40839. defines["SPECULARTERM"] = specularEnabled;
  40840. defines["SHADOWS"] = shadowEnabled;
  40841. // Resetting all other lights if any
  40842. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40843. if (defines["LIGHT" + index] !== undefined) {
  40844. defines["LIGHT" + index] = false;
  40845. defines["HEMILIGHT" + lightIndex] = false;
  40846. defines["POINTLIGHT" + lightIndex] = false;
  40847. defines["DIRLIGHT" + lightIndex] = false;
  40848. defines["SPOTLIGHT" + lightIndex] = false;
  40849. defines["SHADOW" + lightIndex] = false;
  40850. }
  40851. }
  40852. var caps = scene.getEngine().getCaps();
  40853. if (defines["SHADOWFLOAT"] === undefined) {
  40854. needRebuild = true;
  40855. }
  40856. defines["SHADOWFLOAT"] = shadowEnabled &&
  40857. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40858. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40859. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40860. if (needRebuild) {
  40861. defines.rebuild();
  40862. }
  40863. return needNormals;
  40864. };
  40865. /**
  40866. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40867. * that won t be acctive due to defines being turned off.
  40868. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40869. * @param samplersList The samplers list
  40870. * @param defines The defines helping in the list generation
  40871. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40872. */
  40873. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40874. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40875. var uniformsList;
  40876. var uniformBuffersList = null;
  40877. if (uniformsListOrOptions.uniformsNames) {
  40878. var options = uniformsListOrOptions;
  40879. uniformsList = options.uniformsNames;
  40880. uniformBuffersList = options.uniformBuffersNames;
  40881. samplersList = options.samplers;
  40882. defines = options.defines;
  40883. maxSimultaneousLights = options.maxSimultaneousLights;
  40884. }
  40885. else {
  40886. uniformsList = uniformsListOrOptions;
  40887. if (!samplersList) {
  40888. samplersList = [];
  40889. }
  40890. }
  40891. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40892. if (!defines["LIGHT" + lightIndex]) {
  40893. break;
  40894. }
  40895. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  40896. if (uniformBuffersList) {
  40897. uniformBuffersList.push("Light" + lightIndex);
  40898. }
  40899. samplersList.push("shadowSampler" + lightIndex);
  40900. samplersList.push("depthSampler" + lightIndex);
  40901. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  40902. samplersList.push("projectionLightSampler" + lightIndex);
  40903. uniformsList.push("textureProjectionMatrix" + lightIndex);
  40904. }
  40905. }
  40906. if (defines["NUM_MORPH_INFLUENCERS"]) {
  40907. uniformsList.push("morphTargetInfluences");
  40908. }
  40909. };
  40910. /**
  40911. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  40912. * @param defines The defines to update while falling back
  40913. * @param fallbacks The authorized effect fallbacks
  40914. * @param maxSimultaneousLights The maximum number of lights allowed
  40915. * @param rank the current rank of the Effect
  40916. * @returns The newly affected rank
  40917. */
  40918. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  40919. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40920. if (rank === void 0) { rank = 0; }
  40921. var lightFallbackRank = 0;
  40922. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40923. if (!defines["LIGHT" + lightIndex]) {
  40924. break;
  40925. }
  40926. if (lightIndex > 0) {
  40927. lightFallbackRank = rank + lightIndex;
  40928. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  40929. }
  40930. if (!defines["SHADOWS"]) {
  40931. if (defines["SHADOW" + lightIndex]) {
  40932. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  40933. }
  40934. if (defines["SHADOWPCF" + lightIndex]) {
  40935. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  40936. }
  40937. if (defines["SHADOWPCSS" + lightIndex]) {
  40938. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  40939. }
  40940. if (defines["SHADOWPOISSON" + lightIndex]) {
  40941. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  40942. }
  40943. if (defines["SHADOWESM" + lightIndex]) {
  40944. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  40945. }
  40946. }
  40947. }
  40948. return lightFallbackRank++;
  40949. };
  40950. /**
  40951. * Prepares the list of attributes required for morph targets according to the effect defines.
  40952. * @param attribs The current list of supported attribs
  40953. * @param mesh The mesh to prepare the morph targets attributes for
  40954. * @param defines The current Defines of the effect
  40955. */
  40956. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  40957. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  40958. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  40959. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  40960. var manager = mesh.morphTargetManager;
  40961. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  40962. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  40963. for (var index = 0; index < influencers; index++) {
  40964. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  40965. if (normal) {
  40966. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  40967. }
  40968. if (tangent) {
  40969. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  40970. }
  40971. if (attribs.length > maxAttributesCount) {
  40972. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  40973. }
  40974. }
  40975. }
  40976. };
  40977. /**
  40978. * Prepares the list of attributes required for bones according to the effect defines.
  40979. * @param attribs The current list of supported attribs
  40980. * @param mesh The mesh to prepare the bones attributes for
  40981. * @param defines The current Defines of the effect
  40982. * @param fallbacks The current efffect fallback strategy
  40983. */
  40984. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  40985. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  40986. fallbacks.addCPUSkinningFallback(0, mesh);
  40987. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40988. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40989. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  40990. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40991. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40992. }
  40993. }
  40994. };
  40995. /**
  40996. * Prepares the list of attributes required for instances according to the effect defines.
  40997. * @param attribs The current list of supported attribs
  40998. * @param defines The current Defines of the effect
  40999. */
  41000. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41001. if (defines["INSTANCES"]) {
  41002. attribs.push("world0");
  41003. attribs.push("world1");
  41004. attribs.push("world2");
  41005. attribs.push("world3");
  41006. }
  41007. };
  41008. /**
  41009. * Binds the light shadow information to the effect for the given mesh.
  41010. * @param light The light containing the generator
  41011. * @param scene The scene the lights belongs to
  41012. * @param mesh The mesh we are binding the information to render
  41013. * @param lightIndex The light index in the effect used to render the mesh
  41014. * @param effect The effect we are binding the data to
  41015. */
  41016. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41017. if (light.shadowEnabled && mesh.receiveShadows) {
  41018. var shadowGenerator = light.getShadowGenerator();
  41019. if (shadowGenerator) {
  41020. shadowGenerator.bindShadowLight(lightIndex, effect);
  41021. }
  41022. }
  41023. };
  41024. /**
  41025. * Binds the light information to the effect.
  41026. * @param light The light containing the generator
  41027. * @param effect The effect we are binding the data to
  41028. * @param lightIndex The light index in the effect used to render
  41029. */
  41030. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41031. light.transferToEffect(effect, lightIndex + "");
  41032. };
  41033. /**
  41034. * Binds the lights information from the scene to the effect for the given mesh.
  41035. * @param scene The scene the lights belongs to
  41036. * @param mesh The mesh we are binding the information to render
  41037. * @param effect The effect we are binding the data to
  41038. * @param defines The generated defines for the effect
  41039. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41040. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41041. */
  41042. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41043. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41044. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41045. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41046. for (var i = 0; i < len; i++) {
  41047. var light = mesh._lightSources[i];
  41048. var iAsString = i.toString();
  41049. var scaledIntensity = light.getScaledIntensity();
  41050. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41051. MaterialHelper.BindLightProperties(light, effect, i);
  41052. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41053. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41054. if (defines["SPECULARTERM"]) {
  41055. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41056. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41057. }
  41058. // Shadows
  41059. if (scene.shadowsEnabled) {
  41060. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41061. }
  41062. light._uniformBuffer.update();
  41063. }
  41064. };
  41065. /**
  41066. * Binds the fog information from the scene to the effect for the given mesh.
  41067. * @param scene The scene the lights belongs to
  41068. * @param mesh The mesh we are binding the information to render
  41069. * @param effect The effect we are binding the data to
  41070. */
  41071. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41072. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41073. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41074. effect.setColor3("vFogColor", scene.fogColor);
  41075. }
  41076. };
  41077. /**
  41078. * Binds the bones information from the mesh to the effect.
  41079. * @param mesh The mesh we are binding the information to render
  41080. * @param effect The effect we are binding the data to
  41081. */
  41082. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41083. if (!effect || !mesh) {
  41084. return;
  41085. }
  41086. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41087. mesh.computeBonesUsingShaders = false;
  41088. }
  41089. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41090. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41091. if (matrices) {
  41092. effect.setMatrices("mBones", matrices);
  41093. }
  41094. }
  41095. };
  41096. /**
  41097. * Binds the morph targets information from the mesh to the effect.
  41098. * @param abstractMesh The mesh we are binding the information to render
  41099. * @param effect The effect we are binding the data to
  41100. */
  41101. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41102. var manager = abstractMesh.morphTargetManager;
  41103. if (!abstractMesh || !manager) {
  41104. return;
  41105. }
  41106. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41107. };
  41108. /**
  41109. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41110. * @param defines The generated defines used in the effect
  41111. * @param effect The effect we are binding the data to
  41112. * @param scene The scene we are willing to render with logarithmic scale for
  41113. */
  41114. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41115. if (defines["LOGARITHMICDEPTH"]) {
  41116. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41117. }
  41118. };
  41119. /**
  41120. * Binds the clip plane information from the scene to the effect.
  41121. * @param scene The scene the clip plane information are extracted from
  41122. * @param effect The effect we are binding the data to
  41123. */
  41124. MaterialHelper.BindClipPlane = function (effect, scene) {
  41125. if (scene.clipPlane) {
  41126. var clipPlane = scene.clipPlane;
  41127. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41128. }
  41129. };
  41130. return MaterialHelper;
  41131. }());
  41132. BABYLON.MaterialHelper = MaterialHelper;
  41133. })(BABYLON || (BABYLON = {}));
  41134. //# sourceMappingURL=babylon.materialHelper.js.map
  41135. var BABYLON;
  41136. (function (BABYLON) {
  41137. var PushMaterial = /** @class */ (function (_super) {
  41138. __extends(PushMaterial, _super);
  41139. function PushMaterial(name, scene) {
  41140. var _this = _super.call(this, name, scene) || this;
  41141. _this._normalMatrix = new BABYLON.Matrix();
  41142. _this.storeEffectOnSubMeshes = true;
  41143. return _this;
  41144. }
  41145. PushMaterial.prototype.getEffect = function () {
  41146. return this._activeEffect;
  41147. };
  41148. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41149. if (!mesh) {
  41150. return false;
  41151. }
  41152. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41153. return true;
  41154. }
  41155. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41156. };
  41157. /**
  41158. * Binds the given world matrix to the active effect
  41159. *
  41160. * @param world the matrix to bind
  41161. */
  41162. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41163. this._activeEffect.setMatrix("world", world);
  41164. };
  41165. /**
  41166. * Binds the given normal matrix to the active effect
  41167. *
  41168. * @param normalMatrix the matrix to bind
  41169. */
  41170. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41171. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41172. };
  41173. PushMaterial.prototype.bind = function (world, mesh) {
  41174. if (!mesh) {
  41175. return;
  41176. }
  41177. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41178. };
  41179. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41180. if (effect === void 0) { effect = null; }
  41181. _super.prototype._afterBind.call(this, mesh);
  41182. this.getScene()._cachedEffect = effect;
  41183. };
  41184. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41185. if (visibility === void 0) { visibility = 1; }
  41186. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41187. };
  41188. return PushMaterial;
  41189. }(BABYLON.Material));
  41190. BABYLON.PushMaterial = PushMaterial;
  41191. })(BABYLON || (BABYLON = {}));
  41192. //# sourceMappingURL=babylon.pushMaterial.js.map
  41193. var BABYLON;
  41194. (function (BABYLON) {
  41195. /** @hidden */
  41196. var StandardMaterialDefines = /** @class */ (function (_super) {
  41197. __extends(StandardMaterialDefines, _super);
  41198. function StandardMaterialDefines() {
  41199. var _this = _super.call(this) || this;
  41200. _this.MAINUV1 = false;
  41201. _this.MAINUV2 = false;
  41202. _this.DIFFUSE = false;
  41203. _this.DIFFUSEDIRECTUV = 0;
  41204. _this.AMBIENT = false;
  41205. _this.AMBIENTDIRECTUV = 0;
  41206. _this.OPACITY = false;
  41207. _this.OPACITYDIRECTUV = 0;
  41208. _this.OPACITYRGB = false;
  41209. _this.REFLECTION = false;
  41210. _this.EMISSIVE = false;
  41211. _this.EMISSIVEDIRECTUV = 0;
  41212. _this.SPECULAR = false;
  41213. _this.SPECULARDIRECTUV = 0;
  41214. _this.BUMP = false;
  41215. _this.BUMPDIRECTUV = 0;
  41216. _this.PARALLAX = false;
  41217. _this.PARALLAXOCCLUSION = false;
  41218. _this.SPECULAROVERALPHA = false;
  41219. _this.CLIPPLANE = false;
  41220. _this.ALPHATEST = false;
  41221. _this.DEPTHPREPASS = false;
  41222. _this.ALPHAFROMDIFFUSE = false;
  41223. _this.POINTSIZE = false;
  41224. _this.FOG = false;
  41225. _this.SPECULARTERM = false;
  41226. _this.DIFFUSEFRESNEL = false;
  41227. _this.OPACITYFRESNEL = false;
  41228. _this.REFLECTIONFRESNEL = false;
  41229. _this.REFRACTIONFRESNEL = false;
  41230. _this.EMISSIVEFRESNEL = false;
  41231. _this.FRESNEL = false;
  41232. _this.NORMAL = false;
  41233. _this.UV1 = false;
  41234. _this.UV2 = false;
  41235. _this.VERTEXCOLOR = false;
  41236. _this.VERTEXALPHA = false;
  41237. _this.NUM_BONE_INFLUENCERS = 0;
  41238. _this.BonesPerMesh = 0;
  41239. _this.INSTANCES = false;
  41240. _this.GLOSSINESS = false;
  41241. _this.ROUGHNESS = false;
  41242. _this.EMISSIVEASILLUMINATION = false;
  41243. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41244. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41245. _this.LIGHTMAP = false;
  41246. _this.LIGHTMAPDIRECTUV = 0;
  41247. _this.OBJECTSPACE_NORMALMAP = false;
  41248. _this.USELIGHTMAPASSHADOWMAP = false;
  41249. _this.REFLECTIONMAP_3D = false;
  41250. _this.REFLECTIONMAP_SPHERICAL = false;
  41251. _this.REFLECTIONMAP_PLANAR = false;
  41252. _this.REFLECTIONMAP_CUBIC = false;
  41253. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41254. _this.REFLECTIONMAP_PROJECTION = false;
  41255. _this.REFLECTIONMAP_SKYBOX = false;
  41256. _this.REFLECTIONMAP_EXPLICIT = false;
  41257. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41258. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41259. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41260. _this.INVERTCUBICMAP = false;
  41261. _this.LOGARITHMICDEPTH = false;
  41262. _this.REFRACTION = false;
  41263. _this.REFRACTIONMAP_3D = false;
  41264. _this.REFLECTIONOVERALPHA = false;
  41265. _this.TWOSIDEDLIGHTING = false;
  41266. _this.SHADOWFLOAT = false;
  41267. _this.MORPHTARGETS = false;
  41268. _this.MORPHTARGETS_NORMAL = false;
  41269. _this.MORPHTARGETS_TANGENT = false;
  41270. _this.NUM_MORPH_INFLUENCERS = 0;
  41271. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41272. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41273. _this.IMAGEPROCESSING = false;
  41274. _this.VIGNETTE = false;
  41275. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41276. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41277. _this.TONEMAPPING = false;
  41278. _this.CONTRAST = false;
  41279. _this.COLORCURVES = false;
  41280. _this.COLORGRADING = false;
  41281. _this.COLORGRADING3D = false;
  41282. _this.SAMPLER3DGREENDEPTH = false;
  41283. _this.SAMPLER3DBGRMAP = false;
  41284. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41285. /**
  41286. * If the reflection texture on this material is in linear color space
  41287. * @hidden
  41288. */
  41289. _this.IS_REFLECTION_LINEAR = false;
  41290. /**
  41291. * If the refraction texture on this material is in linear color space
  41292. * @hidden
  41293. */
  41294. _this.IS_REFRACTION_LINEAR = false;
  41295. _this.EXPOSURE = false;
  41296. _this.rebuild();
  41297. return _this;
  41298. }
  41299. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41300. var modes = [
  41301. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41302. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41303. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41304. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41305. ];
  41306. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41307. var mode = modes_1[_i];
  41308. this[mode] = (mode === modeToEnable);
  41309. }
  41310. };
  41311. return StandardMaterialDefines;
  41312. }(BABYLON.MaterialDefines));
  41313. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41314. var StandardMaterial = /** @class */ (function (_super) {
  41315. __extends(StandardMaterial, _super);
  41316. function StandardMaterial(name, scene) {
  41317. var _this = _super.call(this, name, scene) || this;
  41318. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41319. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41320. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41321. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41322. _this.specularPower = 64;
  41323. _this._useAlphaFromDiffuseTexture = false;
  41324. _this._useEmissiveAsIllumination = false;
  41325. _this._linkEmissiveWithDiffuse = false;
  41326. _this._useSpecularOverAlpha = false;
  41327. _this._useReflectionOverAlpha = false;
  41328. _this._disableLighting = false;
  41329. _this._useObjectSpaceNormalMap = false;
  41330. _this._useParallax = false;
  41331. _this._useParallaxOcclusion = false;
  41332. _this.parallaxScaleBias = 0.05;
  41333. _this._roughness = 0;
  41334. _this.indexOfRefraction = 0.98;
  41335. _this.invertRefractionY = true;
  41336. /**
  41337. * Defines the alpha limits in alpha test mode
  41338. */
  41339. _this.alphaCutOff = 0.4;
  41340. _this._useLightmapAsShadowmap = false;
  41341. _this._useReflectionFresnelFromSpecular = false;
  41342. _this._useGlossinessFromSpecularMapAlpha = false;
  41343. _this._maxSimultaneousLights = 4;
  41344. /**
  41345. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41346. */
  41347. _this._invertNormalMapX = false;
  41348. /**
  41349. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41350. */
  41351. _this._invertNormalMapY = false;
  41352. /**
  41353. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41354. */
  41355. _this._twoSidedLighting = false;
  41356. _this._renderTargets = new BABYLON.SmartArray(16);
  41357. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41358. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41359. // Setup the default processing configuration to the scene.
  41360. _this._attachImageProcessingConfiguration(null);
  41361. _this.getRenderTargetTextures = function () {
  41362. _this._renderTargets.reset();
  41363. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41364. _this._renderTargets.push(_this._reflectionTexture);
  41365. }
  41366. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41367. _this._renderTargets.push(_this._refractionTexture);
  41368. }
  41369. return _this._renderTargets;
  41370. };
  41371. return _this;
  41372. }
  41373. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41374. /**
  41375. * Gets the image processing configuration used either in this material.
  41376. */
  41377. get: function () {
  41378. return this._imageProcessingConfiguration;
  41379. },
  41380. /**
  41381. * Sets the Default image processing configuration used either in the this material.
  41382. *
  41383. * If sets to null, the scene one is in use.
  41384. */
  41385. set: function (value) {
  41386. this._attachImageProcessingConfiguration(value);
  41387. // Ensure the effect will be rebuilt.
  41388. this._markAllSubMeshesAsTexturesDirty();
  41389. },
  41390. enumerable: true,
  41391. configurable: true
  41392. });
  41393. /**
  41394. * Attaches a new image processing configuration to the Standard Material.
  41395. * @param configuration
  41396. */
  41397. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41398. var _this = this;
  41399. if (configuration === this._imageProcessingConfiguration) {
  41400. return;
  41401. }
  41402. // Detaches observer.
  41403. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41404. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41405. }
  41406. // Pick the scene configuration if needed.
  41407. if (!configuration) {
  41408. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41409. }
  41410. else {
  41411. this._imageProcessingConfiguration = configuration;
  41412. }
  41413. // Attaches observer.
  41414. if (this._imageProcessingConfiguration) {
  41415. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41416. _this._markAllSubMeshesAsImageProcessingDirty();
  41417. });
  41418. }
  41419. };
  41420. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41421. /**
  41422. * Gets wether the color curves effect is enabled.
  41423. */
  41424. get: function () {
  41425. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41426. },
  41427. /**
  41428. * Sets wether the color curves effect is enabled.
  41429. */
  41430. set: function (value) {
  41431. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41432. },
  41433. enumerable: true,
  41434. configurable: true
  41435. });
  41436. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41437. /**
  41438. * Gets wether the color grading effect is enabled.
  41439. */
  41440. get: function () {
  41441. return this.imageProcessingConfiguration.colorGradingEnabled;
  41442. },
  41443. /**
  41444. * Gets wether the color grading effect is enabled.
  41445. */
  41446. set: function (value) {
  41447. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41448. },
  41449. enumerable: true,
  41450. configurable: true
  41451. });
  41452. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41453. /**
  41454. * Gets wether tonemapping is enabled or not.
  41455. */
  41456. get: function () {
  41457. return this._imageProcessingConfiguration.toneMappingEnabled;
  41458. },
  41459. /**
  41460. * Sets wether tonemapping is enabled or not
  41461. */
  41462. set: function (value) {
  41463. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41464. },
  41465. enumerable: true,
  41466. configurable: true
  41467. });
  41468. ;
  41469. ;
  41470. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41471. /**
  41472. * The camera exposure used on this material.
  41473. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41474. * This corresponds to a photographic exposure.
  41475. */
  41476. get: function () {
  41477. return this._imageProcessingConfiguration.exposure;
  41478. },
  41479. /**
  41480. * The camera exposure used on this material.
  41481. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41482. * This corresponds to a photographic exposure.
  41483. */
  41484. set: function (value) {
  41485. this._imageProcessingConfiguration.exposure = value;
  41486. },
  41487. enumerable: true,
  41488. configurable: true
  41489. });
  41490. ;
  41491. ;
  41492. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41493. /**
  41494. * Gets The camera contrast used on this material.
  41495. */
  41496. get: function () {
  41497. return this._imageProcessingConfiguration.contrast;
  41498. },
  41499. /**
  41500. * Sets The camera contrast used on this material.
  41501. */
  41502. set: function (value) {
  41503. this._imageProcessingConfiguration.contrast = value;
  41504. },
  41505. enumerable: true,
  41506. configurable: true
  41507. });
  41508. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41509. /**
  41510. * Gets the Color Grading 2D Lookup Texture.
  41511. */
  41512. get: function () {
  41513. return this._imageProcessingConfiguration.colorGradingTexture;
  41514. },
  41515. /**
  41516. * Sets the Color Grading 2D Lookup Texture.
  41517. */
  41518. set: function (value) {
  41519. this._imageProcessingConfiguration.colorGradingTexture = value;
  41520. },
  41521. enumerable: true,
  41522. configurable: true
  41523. });
  41524. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41525. /**
  41526. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41527. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41528. * 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;
  41529. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41530. */
  41531. get: function () {
  41532. return this._imageProcessingConfiguration.colorCurves;
  41533. },
  41534. /**
  41535. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41536. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41537. * 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;
  41538. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41539. */
  41540. set: function (value) {
  41541. this._imageProcessingConfiguration.colorCurves = value;
  41542. },
  41543. enumerable: true,
  41544. configurable: true
  41545. });
  41546. StandardMaterial.prototype.getClassName = function () {
  41547. return "StandardMaterial";
  41548. };
  41549. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41550. get: function () {
  41551. return this._useLogarithmicDepth;
  41552. },
  41553. set: function (value) {
  41554. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41555. this._markAllSubMeshesAsMiscDirty();
  41556. },
  41557. enumerable: true,
  41558. configurable: true
  41559. });
  41560. StandardMaterial.prototype.needAlphaBlending = function () {
  41561. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41562. };
  41563. StandardMaterial.prototype.needAlphaTesting = function () {
  41564. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41565. };
  41566. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41567. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41568. };
  41569. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41570. return this._diffuseTexture;
  41571. };
  41572. /**
  41573. * Child classes can use it to update shaders
  41574. */
  41575. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41576. if (useInstances === void 0) { useInstances = false; }
  41577. if (subMesh.effect && this.isFrozen) {
  41578. if (this._wasPreviouslyReady && subMesh.effect) {
  41579. return true;
  41580. }
  41581. }
  41582. if (!subMesh._materialDefines) {
  41583. subMesh._materialDefines = new StandardMaterialDefines();
  41584. }
  41585. var scene = this.getScene();
  41586. var defines = subMesh._materialDefines;
  41587. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41588. if (defines._renderId === scene.getRenderId()) {
  41589. return true;
  41590. }
  41591. }
  41592. var engine = scene.getEngine();
  41593. // Lights
  41594. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41595. // Textures
  41596. if (defines._areTexturesDirty) {
  41597. defines._needUVs = false;
  41598. defines.MAINUV1 = false;
  41599. defines.MAINUV2 = false;
  41600. if (scene.texturesEnabled) {
  41601. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41602. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41603. return false;
  41604. }
  41605. else {
  41606. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41607. }
  41608. }
  41609. else {
  41610. defines.DIFFUSE = false;
  41611. }
  41612. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41613. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41614. return false;
  41615. }
  41616. else {
  41617. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41618. }
  41619. }
  41620. else {
  41621. defines.AMBIENT = false;
  41622. }
  41623. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41624. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41625. return false;
  41626. }
  41627. else {
  41628. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41629. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41630. }
  41631. }
  41632. else {
  41633. defines.OPACITY = false;
  41634. }
  41635. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41636. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41637. return false;
  41638. }
  41639. else {
  41640. defines._needNormals = true;
  41641. defines.REFLECTION = true;
  41642. defines.ROUGHNESS = (this._roughness > 0);
  41643. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41644. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41645. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41646. switch (this._reflectionTexture.coordinatesMode) {
  41647. case BABYLON.Texture.EXPLICIT_MODE:
  41648. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41649. break;
  41650. case BABYLON.Texture.PLANAR_MODE:
  41651. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41652. break;
  41653. case BABYLON.Texture.PROJECTION_MODE:
  41654. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41655. break;
  41656. case BABYLON.Texture.SKYBOX_MODE:
  41657. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41658. break;
  41659. case BABYLON.Texture.SPHERICAL_MODE:
  41660. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41661. break;
  41662. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41663. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41664. break;
  41665. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41666. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41667. break;
  41668. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41669. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41670. break;
  41671. case BABYLON.Texture.CUBIC_MODE:
  41672. case BABYLON.Texture.INVCUBIC_MODE:
  41673. default:
  41674. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41675. break;
  41676. }
  41677. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41678. }
  41679. }
  41680. else {
  41681. defines.REFLECTION = false;
  41682. }
  41683. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41684. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41685. return false;
  41686. }
  41687. else {
  41688. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41689. }
  41690. }
  41691. else {
  41692. defines.EMISSIVE = false;
  41693. }
  41694. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41695. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41696. return false;
  41697. }
  41698. else {
  41699. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41700. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41701. }
  41702. }
  41703. else {
  41704. defines.LIGHTMAP = false;
  41705. }
  41706. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41707. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41708. return false;
  41709. }
  41710. else {
  41711. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41712. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41713. }
  41714. }
  41715. else {
  41716. defines.SPECULAR = false;
  41717. }
  41718. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41719. // Bump texure can not be not blocking.
  41720. if (!this._bumpTexture.isReady()) {
  41721. return false;
  41722. }
  41723. else {
  41724. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41725. defines.PARALLAX = this._useParallax;
  41726. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41727. }
  41728. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41729. }
  41730. else {
  41731. defines.BUMP = false;
  41732. }
  41733. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41734. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41735. return false;
  41736. }
  41737. else {
  41738. defines._needUVs = true;
  41739. defines.REFRACTION = true;
  41740. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41741. }
  41742. }
  41743. else {
  41744. defines.REFRACTION = false;
  41745. }
  41746. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41747. }
  41748. else {
  41749. defines.DIFFUSE = false;
  41750. defines.AMBIENT = false;
  41751. defines.OPACITY = false;
  41752. defines.REFLECTION = false;
  41753. defines.EMISSIVE = false;
  41754. defines.LIGHTMAP = false;
  41755. defines.BUMP = false;
  41756. defines.REFRACTION = false;
  41757. }
  41758. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41759. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41760. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41761. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41762. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41763. }
  41764. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41765. if (!this._imageProcessingConfiguration.isReady()) {
  41766. return false;
  41767. }
  41768. this._imageProcessingConfiguration.prepareDefines(defines);
  41769. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41770. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41771. }
  41772. if (defines._areFresnelDirty) {
  41773. if (StandardMaterial.FresnelEnabled) {
  41774. // Fresnel
  41775. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41776. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41777. this._reflectionFresnelParameters) {
  41778. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41779. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41780. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41781. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41782. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41783. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41784. defines._needNormals = true;
  41785. defines.FRESNEL = true;
  41786. }
  41787. }
  41788. else {
  41789. defines.FRESNEL = false;
  41790. }
  41791. }
  41792. // Misc.
  41793. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41794. // Attribs
  41795. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41796. // Values that need to be evaluated on every frame
  41797. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41798. // Get correct effect
  41799. if (defines.isDirty) {
  41800. defines.markAsProcessed();
  41801. scene.resetCachedMaterial();
  41802. // Fallbacks
  41803. var fallbacks = new BABYLON.EffectFallbacks();
  41804. if (defines.REFLECTION) {
  41805. fallbacks.addFallback(0, "REFLECTION");
  41806. }
  41807. if (defines.SPECULAR) {
  41808. fallbacks.addFallback(0, "SPECULAR");
  41809. }
  41810. if (defines.BUMP) {
  41811. fallbacks.addFallback(0, "BUMP");
  41812. }
  41813. if (defines.PARALLAX) {
  41814. fallbacks.addFallback(1, "PARALLAX");
  41815. }
  41816. if (defines.PARALLAXOCCLUSION) {
  41817. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41818. }
  41819. if (defines.SPECULAROVERALPHA) {
  41820. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41821. }
  41822. if (defines.FOG) {
  41823. fallbacks.addFallback(1, "FOG");
  41824. }
  41825. if (defines.POINTSIZE) {
  41826. fallbacks.addFallback(0, "POINTSIZE");
  41827. }
  41828. if (defines.LOGARITHMICDEPTH) {
  41829. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41830. }
  41831. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41832. if (defines.SPECULARTERM) {
  41833. fallbacks.addFallback(0, "SPECULARTERM");
  41834. }
  41835. if (defines.DIFFUSEFRESNEL) {
  41836. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41837. }
  41838. if (defines.OPACITYFRESNEL) {
  41839. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41840. }
  41841. if (defines.REFLECTIONFRESNEL) {
  41842. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41843. }
  41844. if (defines.EMISSIVEFRESNEL) {
  41845. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41846. }
  41847. if (defines.FRESNEL) {
  41848. fallbacks.addFallback(4, "FRESNEL");
  41849. }
  41850. //Attributes
  41851. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41852. if (defines.NORMAL) {
  41853. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41854. }
  41855. if (defines.UV1) {
  41856. attribs.push(BABYLON.VertexBuffer.UVKind);
  41857. }
  41858. if (defines.UV2) {
  41859. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41860. }
  41861. if (defines.VERTEXCOLOR) {
  41862. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41863. }
  41864. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41865. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41866. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41867. var shaderName = "default";
  41868. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41869. "vFogInfos", "vFogColor", "pointSize",
  41870. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41871. "mBones",
  41872. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41873. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41874. "vReflectionPosition", "vReflectionSize",
  41875. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  41876. ];
  41877. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41878. var uniformBuffers = ["Material", "Scene"];
  41879. if (BABYLON.ImageProcessingConfiguration) {
  41880. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41881. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41882. }
  41883. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41884. uniformsNames: uniforms,
  41885. uniformBuffersNames: uniformBuffers,
  41886. samplers: samplers,
  41887. defines: defines,
  41888. maxSimultaneousLights: this._maxSimultaneousLights
  41889. });
  41890. if (this.customShaderNameResolve) {
  41891. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41892. }
  41893. var join = defines.toString();
  41894. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41895. attributes: attribs,
  41896. uniformsNames: uniforms,
  41897. uniformBuffersNames: uniformBuffers,
  41898. samplers: samplers,
  41899. defines: join,
  41900. fallbacks: fallbacks,
  41901. onCompiled: this.onCompiled,
  41902. onError: this.onError,
  41903. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41904. }, engine), defines);
  41905. this.buildUniformLayout();
  41906. }
  41907. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41908. return false;
  41909. }
  41910. defines._renderId = scene.getRenderId();
  41911. this._wasPreviouslyReady = true;
  41912. return true;
  41913. };
  41914. StandardMaterial.prototype.buildUniformLayout = function () {
  41915. // Order is important !
  41916. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  41917. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  41918. this._uniformBuffer.addUniform("opacityParts", 4);
  41919. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  41920. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  41921. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  41922. this._uniformBuffer.addUniform("refractionRightColor", 4);
  41923. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  41924. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  41925. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  41926. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  41927. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41928. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41929. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41930. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41931. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41932. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41933. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  41934. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41935. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  41936. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41937. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41938. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41939. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41940. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41941. this._uniformBuffer.addUniform("specularMatrix", 16);
  41942. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41943. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41944. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41945. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41946. this._uniformBuffer.addUniform("vSpecularColor", 4);
  41947. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41948. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  41949. this._uniformBuffer.addUniform("pointSize", 1);
  41950. this._uniformBuffer.create();
  41951. };
  41952. StandardMaterial.prototype.unbind = function () {
  41953. if (this._activeEffect) {
  41954. var needFlag = false;
  41955. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41956. this._activeEffect.setTexture("reflection2DSampler", null);
  41957. needFlag = true;
  41958. }
  41959. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41960. this._activeEffect.setTexture("refraction2DSampler", null);
  41961. needFlag = true;
  41962. }
  41963. if (needFlag) {
  41964. this._markAllSubMeshesAsTexturesDirty();
  41965. }
  41966. }
  41967. _super.prototype.unbind.call(this);
  41968. };
  41969. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41970. var scene = this.getScene();
  41971. var defines = subMesh._materialDefines;
  41972. if (!defines) {
  41973. return;
  41974. }
  41975. var effect = subMesh.effect;
  41976. if (!effect) {
  41977. return;
  41978. }
  41979. this._activeEffect = effect;
  41980. // Matrices
  41981. this.bindOnlyWorldMatrix(world);
  41982. // Normal Matrix
  41983. if (defines.OBJECTSPACE_NORMALMAP) {
  41984. world.toNormalMatrix(this._normalMatrix);
  41985. this.bindOnlyNormalMatrix(this._normalMatrix);
  41986. }
  41987. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41988. // Bones
  41989. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  41990. if (mustRebind) {
  41991. this._uniformBuffer.bindToEffect(effect, "Material");
  41992. this.bindViewProjection(effect);
  41993. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41994. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  41995. // Fresnel
  41996. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  41997. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  41998. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  41999. }
  42000. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42001. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42002. }
  42003. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42004. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42005. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42006. }
  42007. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42008. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42009. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42010. }
  42011. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42012. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42013. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42014. }
  42015. }
  42016. // Textures
  42017. if (scene.texturesEnabled) {
  42018. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42019. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42020. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42021. if (this._diffuseTexture.hasAlpha) {
  42022. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42023. }
  42024. }
  42025. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42026. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42027. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42028. }
  42029. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42030. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42031. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42032. }
  42033. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42034. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42035. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42036. if (this._reflectionTexture.boundingBoxSize) {
  42037. var cubeTexture = this._reflectionTexture;
  42038. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42039. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42040. }
  42041. }
  42042. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42043. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42044. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42045. }
  42046. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42047. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42048. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42049. }
  42050. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42051. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42052. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42053. }
  42054. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42055. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42056. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42057. if (scene._mirroredCameraPosition) {
  42058. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42059. }
  42060. else {
  42061. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42062. }
  42063. }
  42064. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42065. var depth = 1.0;
  42066. if (!this._refractionTexture.isCube) {
  42067. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42068. if (this._refractionTexture.depth) {
  42069. depth = this._refractionTexture.depth;
  42070. }
  42071. }
  42072. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42073. }
  42074. }
  42075. // Point size
  42076. if (this.pointsCloud) {
  42077. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42078. }
  42079. if (defines.SPECULARTERM) {
  42080. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42081. }
  42082. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42083. // Diffuse
  42084. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42085. }
  42086. // Textures
  42087. if (scene.texturesEnabled) {
  42088. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42089. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42090. }
  42091. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42092. effect.setTexture("ambientSampler", this._ambientTexture);
  42093. }
  42094. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42095. effect.setTexture("opacitySampler", this._opacityTexture);
  42096. }
  42097. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42098. if (this._reflectionTexture.isCube) {
  42099. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42100. }
  42101. else {
  42102. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42103. }
  42104. }
  42105. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42106. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42107. }
  42108. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42109. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42110. }
  42111. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42112. effect.setTexture("specularSampler", this._specularTexture);
  42113. }
  42114. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42115. effect.setTexture("bumpSampler", this._bumpTexture);
  42116. }
  42117. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42118. var depth = 1.0;
  42119. if (this._refractionTexture.isCube) {
  42120. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42121. }
  42122. else {
  42123. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42124. }
  42125. }
  42126. }
  42127. // Clip plane
  42128. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42129. // Colors
  42130. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42131. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42132. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42133. }
  42134. if (mustRebind || !this.isFrozen) {
  42135. // Lights
  42136. if (scene.lightsEnabled && !this._disableLighting) {
  42137. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42138. }
  42139. // View
  42140. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42141. this.bindView(effect);
  42142. }
  42143. // Fog
  42144. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42145. // Morph targets
  42146. if (defines.NUM_MORPH_INFLUENCERS) {
  42147. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42148. }
  42149. // Log. depth
  42150. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42151. // image processing
  42152. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42153. this._imageProcessingConfiguration.bind(this._activeEffect);
  42154. }
  42155. }
  42156. this._uniformBuffer.update();
  42157. this._afterBind(mesh, this._activeEffect);
  42158. };
  42159. StandardMaterial.prototype.getAnimatables = function () {
  42160. var results = [];
  42161. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42162. results.push(this._diffuseTexture);
  42163. }
  42164. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42165. results.push(this._ambientTexture);
  42166. }
  42167. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42168. results.push(this._opacityTexture);
  42169. }
  42170. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42171. results.push(this._reflectionTexture);
  42172. }
  42173. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42174. results.push(this._emissiveTexture);
  42175. }
  42176. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42177. results.push(this._specularTexture);
  42178. }
  42179. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42180. results.push(this._bumpTexture);
  42181. }
  42182. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42183. results.push(this._lightmapTexture);
  42184. }
  42185. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42186. results.push(this._refractionTexture);
  42187. }
  42188. return results;
  42189. };
  42190. StandardMaterial.prototype.getActiveTextures = function () {
  42191. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42192. if (this._diffuseTexture) {
  42193. activeTextures.push(this._diffuseTexture);
  42194. }
  42195. if (this._ambientTexture) {
  42196. activeTextures.push(this._ambientTexture);
  42197. }
  42198. if (this._opacityTexture) {
  42199. activeTextures.push(this._opacityTexture);
  42200. }
  42201. if (this._reflectionTexture) {
  42202. activeTextures.push(this._reflectionTexture);
  42203. }
  42204. if (this._emissiveTexture) {
  42205. activeTextures.push(this._emissiveTexture);
  42206. }
  42207. if (this._specularTexture) {
  42208. activeTextures.push(this._specularTexture);
  42209. }
  42210. if (this._bumpTexture) {
  42211. activeTextures.push(this._bumpTexture);
  42212. }
  42213. if (this._lightmapTexture) {
  42214. activeTextures.push(this._lightmapTexture);
  42215. }
  42216. if (this._refractionTexture) {
  42217. activeTextures.push(this._refractionTexture);
  42218. }
  42219. return activeTextures;
  42220. };
  42221. StandardMaterial.prototype.hasTexture = function (texture) {
  42222. if (_super.prototype.hasTexture.call(this, texture)) {
  42223. return true;
  42224. }
  42225. if (this._diffuseTexture === texture) {
  42226. return true;
  42227. }
  42228. if (this._ambientTexture === texture) {
  42229. return true;
  42230. }
  42231. if (this._opacityTexture === texture) {
  42232. return true;
  42233. }
  42234. if (this._reflectionTexture === texture) {
  42235. return true;
  42236. }
  42237. if (this._emissiveTexture === texture) {
  42238. return true;
  42239. }
  42240. if (this._specularTexture === texture) {
  42241. return true;
  42242. }
  42243. if (this._bumpTexture === texture) {
  42244. return true;
  42245. }
  42246. if (this._lightmapTexture === texture) {
  42247. return true;
  42248. }
  42249. if (this._refractionTexture === texture) {
  42250. return true;
  42251. }
  42252. return false;
  42253. };
  42254. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42255. if (forceDisposeTextures) {
  42256. if (this._diffuseTexture) {
  42257. this._diffuseTexture.dispose();
  42258. }
  42259. if (this._ambientTexture) {
  42260. this._ambientTexture.dispose();
  42261. }
  42262. if (this._opacityTexture) {
  42263. this._opacityTexture.dispose();
  42264. }
  42265. if (this._reflectionTexture) {
  42266. this._reflectionTexture.dispose();
  42267. }
  42268. if (this._emissiveTexture) {
  42269. this._emissiveTexture.dispose();
  42270. }
  42271. if (this._specularTexture) {
  42272. this._specularTexture.dispose();
  42273. }
  42274. if (this._bumpTexture) {
  42275. this._bumpTexture.dispose();
  42276. }
  42277. if (this._lightmapTexture) {
  42278. this._lightmapTexture.dispose();
  42279. }
  42280. if (this._refractionTexture) {
  42281. this._refractionTexture.dispose();
  42282. }
  42283. }
  42284. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42285. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42286. }
  42287. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42288. };
  42289. StandardMaterial.prototype.clone = function (name) {
  42290. var _this = this;
  42291. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42292. result.name = name;
  42293. result.id = name;
  42294. return result;
  42295. };
  42296. StandardMaterial.prototype.serialize = function () {
  42297. return BABYLON.SerializationHelper.Serialize(this);
  42298. };
  42299. // Statics
  42300. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42301. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42302. };
  42303. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42304. get: function () {
  42305. return StandardMaterial._DiffuseTextureEnabled;
  42306. },
  42307. set: function (value) {
  42308. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42309. return;
  42310. }
  42311. StandardMaterial._DiffuseTextureEnabled = value;
  42312. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42313. },
  42314. enumerable: true,
  42315. configurable: true
  42316. });
  42317. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42318. get: function () {
  42319. return StandardMaterial._AmbientTextureEnabled;
  42320. },
  42321. set: function (value) {
  42322. if (StandardMaterial._AmbientTextureEnabled === value) {
  42323. return;
  42324. }
  42325. StandardMaterial._AmbientTextureEnabled = value;
  42326. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42327. },
  42328. enumerable: true,
  42329. configurable: true
  42330. });
  42331. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42332. get: function () {
  42333. return StandardMaterial._OpacityTextureEnabled;
  42334. },
  42335. set: function (value) {
  42336. if (StandardMaterial._OpacityTextureEnabled === value) {
  42337. return;
  42338. }
  42339. StandardMaterial._OpacityTextureEnabled = value;
  42340. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42341. },
  42342. enumerable: true,
  42343. configurable: true
  42344. });
  42345. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42346. get: function () {
  42347. return StandardMaterial._ReflectionTextureEnabled;
  42348. },
  42349. set: function (value) {
  42350. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42351. return;
  42352. }
  42353. StandardMaterial._ReflectionTextureEnabled = value;
  42354. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42355. },
  42356. enumerable: true,
  42357. configurable: true
  42358. });
  42359. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42360. get: function () {
  42361. return StandardMaterial._EmissiveTextureEnabled;
  42362. },
  42363. set: function (value) {
  42364. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42365. return;
  42366. }
  42367. StandardMaterial._EmissiveTextureEnabled = value;
  42368. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42369. },
  42370. enumerable: true,
  42371. configurable: true
  42372. });
  42373. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42374. get: function () {
  42375. return StandardMaterial._SpecularTextureEnabled;
  42376. },
  42377. set: function (value) {
  42378. if (StandardMaterial._SpecularTextureEnabled === value) {
  42379. return;
  42380. }
  42381. StandardMaterial._SpecularTextureEnabled = value;
  42382. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42383. },
  42384. enumerable: true,
  42385. configurable: true
  42386. });
  42387. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42388. get: function () {
  42389. return StandardMaterial._BumpTextureEnabled;
  42390. },
  42391. set: function (value) {
  42392. if (StandardMaterial._BumpTextureEnabled === value) {
  42393. return;
  42394. }
  42395. StandardMaterial._BumpTextureEnabled = value;
  42396. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42397. },
  42398. enumerable: true,
  42399. configurable: true
  42400. });
  42401. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42402. get: function () {
  42403. return StandardMaterial._LightmapTextureEnabled;
  42404. },
  42405. set: function (value) {
  42406. if (StandardMaterial._LightmapTextureEnabled === value) {
  42407. return;
  42408. }
  42409. StandardMaterial._LightmapTextureEnabled = value;
  42410. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42411. },
  42412. enumerable: true,
  42413. configurable: true
  42414. });
  42415. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42416. get: function () {
  42417. return StandardMaterial._RefractionTextureEnabled;
  42418. },
  42419. set: function (value) {
  42420. if (StandardMaterial._RefractionTextureEnabled === value) {
  42421. return;
  42422. }
  42423. StandardMaterial._RefractionTextureEnabled = value;
  42424. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42425. },
  42426. enumerable: true,
  42427. configurable: true
  42428. });
  42429. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42430. get: function () {
  42431. return StandardMaterial._ColorGradingTextureEnabled;
  42432. },
  42433. set: function (value) {
  42434. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42435. return;
  42436. }
  42437. StandardMaterial._ColorGradingTextureEnabled = value;
  42438. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42439. },
  42440. enumerable: true,
  42441. configurable: true
  42442. });
  42443. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42444. get: function () {
  42445. return StandardMaterial._FresnelEnabled;
  42446. },
  42447. set: function (value) {
  42448. if (StandardMaterial._FresnelEnabled === value) {
  42449. return;
  42450. }
  42451. StandardMaterial._FresnelEnabled = value;
  42452. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42453. },
  42454. enumerable: true,
  42455. configurable: true
  42456. });
  42457. // Flags used to enable or disable a type of texture for all Standard Materials
  42458. StandardMaterial._DiffuseTextureEnabled = true;
  42459. StandardMaterial._AmbientTextureEnabled = true;
  42460. StandardMaterial._OpacityTextureEnabled = true;
  42461. StandardMaterial._ReflectionTextureEnabled = true;
  42462. StandardMaterial._EmissiveTextureEnabled = true;
  42463. StandardMaterial._SpecularTextureEnabled = true;
  42464. StandardMaterial._BumpTextureEnabled = true;
  42465. StandardMaterial._LightmapTextureEnabled = true;
  42466. StandardMaterial._RefractionTextureEnabled = true;
  42467. StandardMaterial._ColorGradingTextureEnabled = true;
  42468. StandardMaterial._FresnelEnabled = true;
  42469. __decorate([
  42470. BABYLON.serializeAsTexture("diffuseTexture")
  42471. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42472. __decorate([
  42473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42474. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42475. __decorate([
  42476. BABYLON.serializeAsTexture("ambientTexture")
  42477. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42478. __decorate([
  42479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42480. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42481. __decorate([
  42482. BABYLON.serializeAsTexture("opacityTexture")
  42483. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42484. __decorate([
  42485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42486. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42487. __decorate([
  42488. BABYLON.serializeAsTexture("reflectionTexture")
  42489. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42490. __decorate([
  42491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42492. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42493. __decorate([
  42494. BABYLON.serializeAsTexture("emissiveTexture")
  42495. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42496. __decorate([
  42497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42498. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42499. __decorate([
  42500. BABYLON.serializeAsTexture("specularTexture")
  42501. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42502. __decorate([
  42503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42504. ], StandardMaterial.prototype, "specularTexture", void 0);
  42505. __decorate([
  42506. BABYLON.serializeAsTexture("bumpTexture")
  42507. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42508. __decorate([
  42509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42510. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42511. __decorate([
  42512. BABYLON.serializeAsTexture("lightmapTexture")
  42513. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42514. __decorate([
  42515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42516. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42517. __decorate([
  42518. BABYLON.serializeAsTexture("refractionTexture")
  42519. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42520. __decorate([
  42521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42522. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42523. __decorate([
  42524. BABYLON.serializeAsColor3("ambient")
  42525. ], StandardMaterial.prototype, "ambientColor", void 0);
  42526. __decorate([
  42527. BABYLON.serializeAsColor3("diffuse")
  42528. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42529. __decorate([
  42530. BABYLON.serializeAsColor3("specular")
  42531. ], StandardMaterial.prototype, "specularColor", void 0);
  42532. __decorate([
  42533. BABYLON.serializeAsColor3("emissive")
  42534. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42535. __decorate([
  42536. BABYLON.serialize()
  42537. ], StandardMaterial.prototype, "specularPower", void 0);
  42538. __decorate([
  42539. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42540. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42541. __decorate([
  42542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42543. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42544. __decorate([
  42545. BABYLON.serialize("useEmissiveAsIllumination")
  42546. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42547. __decorate([
  42548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42549. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42550. __decorate([
  42551. BABYLON.serialize("linkEmissiveWithDiffuse")
  42552. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42553. __decorate([
  42554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42555. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42556. __decorate([
  42557. BABYLON.serialize("useSpecularOverAlpha")
  42558. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42559. __decorate([
  42560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42561. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42562. __decorate([
  42563. BABYLON.serialize("useReflectionOverAlpha")
  42564. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42565. __decorate([
  42566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42567. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42568. __decorate([
  42569. BABYLON.serialize("disableLighting")
  42570. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42571. __decorate([
  42572. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42573. ], StandardMaterial.prototype, "disableLighting", void 0);
  42574. __decorate([
  42575. BABYLON.serialize("useObjectSpaceNormalMap")
  42576. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42577. __decorate([
  42578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42579. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42580. __decorate([
  42581. BABYLON.serialize("useParallax")
  42582. ], StandardMaterial.prototype, "_useParallax", void 0);
  42583. __decorate([
  42584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42585. ], StandardMaterial.prototype, "useParallax", void 0);
  42586. __decorate([
  42587. BABYLON.serialize("useParallaxOcclusion")
  42588. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42589. __decorate([
  42590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42591. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42592. __decorate([
  42593. BABYLON.serialize()
  42594. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42595. __decorate([
  42596. BABYLON.serialize("roughness")
  42597. ], StandardMaterial.prototype, "_roughness", void 0);
  42598. __decorate([
  42599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42600. ], StandardMaterial.prototype, "roughness", void 0);
  42601. __decorate([
  42602. BABYLON.serialize()
  42603. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42604. __decorate([
  42605. BABYLON.serialize()
  42606. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42607. __decorate([
  42608. BABYLON.serialize()
  42609. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42610. __decorate([
  42611. BABYLON.serialize("useLightmapAsShadowmap")
  42612. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42613. __decorate([
  42614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42615. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42616. __decorate([
  42617. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42618. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42619. __decorate([
  42620. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42621. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42622. __decorate([
  42623. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42624. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42625. __decorate([
  42626. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42627. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42628. __decorate([
  42629. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42630. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42631. __decorate([
  42632. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42633. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42634. __decorate([
  42635. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42636. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42637. __decorate([
  42638. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42639. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42640. __decorate([
  42641. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42642. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42643. __decorate([
  42644. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42645. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42646. __decorate([
  42647. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42648. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42649. __decorate([
  42650. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42651. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42652. __decorate([
  42653. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42654. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42655. __decorate([
  42656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42657. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42658. __decorate([
  42659. BABYLON.serialize("maxSimultaneousLights")
  42660. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42661. __decorate([
  42662. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42663. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42664. __decorate([
  42665. BABYLON.serialize("invertNormalMapX")
  42666. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42667. __decorate([
  42668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42669. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42670. __decorate([
  42671. BABYLON.serialize("invertNormalMapY")
  42672. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42673. __decorate([
  42674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42675. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42676. __decorate([
  42677. BABYLON.serialize("twoSidedLighting")
  42678. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42679. __decorate([
  42680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42681. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42682. __decorate([
  42683. BABYLON.serialize()
  42684. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42685. return StandardMaterial;
  42686. }(BABYLON.PushMaterial));
  42687. BABYLON.StandardMaterial = StandardMaterial;
  42688. })(BABYLON || (BABYLON = {}));
  42689. //# sourceMappingURL=babylon.standardMaterial.js.map
  42690. var BABYLON;
  42691. (function (BABYLON) {
  42692. /**
  42693. * Class representing spherical polynomial coefficients to the 3rd degree
  42694. */
  42695. var SphericalPolynomial = /** @class */ (function () {
  42696. function SphericalPolynomial() {
  42697. /**
  42698. * The x coefficients of the spherical polynomial
  42699. */
  42700. this.x = BABYLON.Vector3.Zero();
  42701. /**
  42702. * The y coefficients of the spherical polynomial
  42703. */
  42704. this.y = BABYLON.Vector3.Zero();
  42705. /**
  42706. * The z coefficients of the spherical polynomial
  42707. */
  42708. this.z = BABYLON.Vector3.Zero();
  42709. /**
  42710. * The xx coefficients of the spherical polynomial
  42711. */
  42712. this.xx = BABYLON.Vector3.Zero();
  42713. /**
  42714. * The yy coefficients of the spherical polynomial
  42715. */
  42716. this.yy = BABYLON.Vector3.Zero();
  42717. /**
  42718. * The zz coefficients of the spherical polynomial
  42719. */
  42720. this.zz = BABYLON.Vector3.Zero();
  42721. /**
  42722. * The xy coefficients of the spherical polynomial
  42723. */
  42724. this.xy = BABYLON.Vector3.Zero();
  42725. /**
  42726. * The yz coefficients of the spherical polynomial
  42727. */
  42728. this.yz = BABYLON.Vector3.Zero();
  42729. /**
  42730. * The zx coefficients of the spherical polynomial
  42731. */
  42732. this.zx = BABYLON.Vector3.Zero();
  42733. }
  42734. /**
  42735. * Adds an ambient color to the spherical polynomial
  42736. * @param color the color to add
  42737. */
  42738. SphericalPolynomial.prototype.addAmbient = function (color) {
  42739. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42740. this.xx = this.xx.add(colorVector);
  42741. this.yy = this.yy.add(colorVector);
  42742. this.zz = this.zz.add(colorVector);
  42743. };
  42744. /**
  42745. * Scales the spherical polynomial by the given amount
  42746. * @param scale the amount to scale
  42747. */
  42748. SphericalPolynomial.prototype.scale = function (scale) {
  42749. this.x = this.x.scale(scale);
  42750. this.y = this.y.scale(scale);
  42751. this.z = this.z.scale(scale);
  42752. this.xx = this.xx.scale(scale);
  42753. this.yy = this.yy.scale(scale);
  42754. this.zz = this.zz.scale(scale);
  42755. this.yz = this.yz.scale(scale);
  42756. this.zx = this.zx.scale(scale);
  42757. this.xy = this.xy.scale(scale);
  42758. };
  42759. /**
  42760. * Gets the spherical polynomial from harmonics
  42761. * @param harmonics the spherical harmonics
  42762. * @returns the spherical polynomial
  42763. */
  42764. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42765. var result = new SphericalPolynomial();
  42766. result.x = harmonics.l11.scale(1.02333);
  42767. result.y = harmonics.l1_1.scale(1.02333);
  42768. result.z = harmonics.l10.scale(1.02333);
  42769. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42770. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42771. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42772. result.yz = harmonics.l2_1.scale(0.858086);
  42773. result.zx = harmonics.l21.scale(0.858086);
  42774. result.xy = harmonics.l2_2.scale(0.858086);
  42775. result.scale(1.0 / Math.PI);
  42776. return result;
  42777. };
  42778. /**
  42779. * Constructs a spherical polynomial from an array.
  42780. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42781. * @returns the spherical polynomial
  42782. */
  42783. SphericalPolynomial.FromArray = function (data) {
  42784. var sp = new SphericalPolynomial();
  42785. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42786. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42787. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42788. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42789. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42790. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42791. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42792. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42793. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42794. return sp;
  42795. };
  42796. return SphericalPolynomial;
  42797. }());
  42798. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42799. /**
  42800. * Class representing spherical harmonics coefficients to the 3rd degree
  42801. */
  42802. var SphericalHarmonics = /** @class */ (function () {
  42803. function SphericalHarmonics() {
  42804. /**
  42805. * The l0,0 coefficients of the spherical harmonics
  42806. */
  42807. this.l00 = BABYLON.Vector3.Zero();
  42808. /**
  42809. * The l1,-1 coefficients of the spherical harmonics
  42810. */
  42811. this.l1_1 = BABYLON.Vector3.Zero();
  42812. /**
  42813. * The l1,0 coefficients of the spherical harmonics
  42814. */
  42815. this.l10 = BABYLON.Vector3.Zero();
  42816. /**
  42817. * The l1,1 coefficients of the spherical harmonics
  42818. */
  42819. this.l11 = BABYLON.Vector3.Zero();
  42820. /**
  42821. * The l2,-2 coefficients of the spherical harmonics
  42822. */
  42823. this.l2_2 = BABYLON.Vector3.Zero();
  42824. /**
  42825. * The l2,-1 coefficients of the spherical harmonics
  42826. */
  42827. this.l2_1 = BABYLON.Vector3.Zero();
  42828. /**
  42829. * The l2,0 coefficients of the spherical harmonics
  42830. */
  42831. this.l20 = BABYLON.Vector3.Zero();
  42832. /**
  42833. * The l2,1 coefficients of the spherical harmonics
  42834. */
  42835. this.l21 = BABYLON.Vector3.Zero();
  42836. /**
  42837. * The l2,2 coefficients of the spherical harmonics
  42838. */
  42839. this.lL22 = BABYLON.Vector3.Zero();
  42840. }
  42841. /**
  42842. * Adds a light to the spherical harmonics
  42843. * @param direction the direction of the light
  42844. * @param color the color of the light
  42845. * @param deltaSolidAngle the delta solid angle of the light
  42846. */
  42847. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  42848. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42849. var c = colorVector.scale(deltaSolidAngle);
  42850. this.l00 = this.l00.add(c.scale(0.282095));
  42851. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  42852. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  42853. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  42854. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  42855. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  42856. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  42857. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  42858. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  42859. };
  42860. /**
  42861. * Scales the spherical harmonics by the given amount
  42862. * @param scale the amount to scale
  42863. */
  42864. SphericalHarmonics.prototype.scale = function (scale) {
  42865. this.l00 = this.l00.scale(scale);
  42866. this.l1_1 = this.l1_1.scale(scale);
  42867. this.l10 = this.l10.scale(scale);
  42868. this.l11 = this.l11.scale(scale);
  42869. this.l2_2 = this.l2_2.scale(scale);
  42870. this.l2_1 = this.l2_1.scale(scale);
  42871. this.l20 = this.l20.scale(scale);
  42872. this.l21 = this.l21.scale(scale);
  42873. this.lL22 = this.lL22.scale(scale);
  42874. };
  42875. /**
  42876. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  42877. *
  42878. * ```
  42879. * E_lm = A_l * L_lm
  42880. * ```
  42881. *
  42882. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  42883. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  42884. * the scaling factors are given in equation 9.
  42885. */
  42886. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  42887. // Constant (Band 0)
  42888. this.l00 = this.l00.scale(3.141593);
  42889. // Linear (Band 1)
  42890. this.l1_1 = this.l1_1.scale(2.094395);
  42891. this.l10 = this.l10.scale(2.094395);
  42892. this.l11 = this.l11.scale(2.094395);
  42893. // Quadratic (Band 2)
  42894. this.l2_2 = this.l2_2.scale(0.785398);
  42895. this.l2_1 = this.l2_1.scale(0.785398);
  42896. this.l20 = this.l20.scale(0.785398);
  42897. this.l21 = this.l21.scale(0.785398);
  42898. this.lL22 = this.lL22.scale(0.785398);
  42899. };
  42900. /**
  42901. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  42902. *
  42903. * ```
  42904. * L = (1/pi) * E * rho
  42905. * ```
  42906. *
  42907. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  42908. */
  42909. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  42910. this.scale(1.0 / Math.PI);
  42911. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  42912. // (The pixel shader must apply albedo after texture fetches, etc).
  42913. };
  42914. /**
  42915. * Gets the spherical harmonics from polynomial
  42916. * @param polynomial the spherical polynomial
  42917. * @returns the spherical harmonics
  42918. */
  42919. SphericalHarmonics.FromPolynomial = function (polynomial) {
  42920. var result = new SphericalHarmonics();
  42921. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  42922. result.l1_1 = polynomial.y.scale(0.977204);
  42923. result.l10 = polynomial.z.scale(0.977204);
  42924. result.l11 = polynomial.x.scale(0.977204);
  42925. result.l2_2 = polynomial.xy.scale(1.16538);
  42926. result.l2_1 = polynomial.yz.scale(1.16538);
  42927. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  42928. result.l21 = polynomial.zx.scale(1.16538);
  42929. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  42930. result.scale(Math.PI);
  42931. return result;
  42932. };
  42933. /**
  42934. * Constructs a spherical harmonics from an array.
  42935. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  42936. * @returns the spherical harmonics
  42937. */
  42938. SphericalHarmonics.FromArray = function (data) {
  42939. var sh = new SphericalHarmonics();
  42940. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  42941. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  42942. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  42943. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  42944. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  42945. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  42946. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  42947. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  42948. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  42949. return sh;
  42950. };
  42951. return SphericalHarmonics;
  42952. }());
  42953. BABYLON.SphericalHarmonics = SphericalHarmonics;
  42954. })(BABYLON || (BABYLON = {}));
  42955. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  42956. var BABYLON;
  42957. (function (BABYLON) {
  42958. var FileFaceOrientation = /** @class */ (function () {
  42959. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42960. this.name = name;
  42961. this.worldAxisForNormal = worldAxisForNormal;
  42962. this.worldAxisForFileX = worldAxisForFileX;
  42963. this.worldAxisForFileY = worldAxisForFileY;
  42964. }
  42965. return FileFaceOrientation;
  42966. }());
  42967. ;
  42968. /**
  42969. * Helper class dealing with the extraction of spherical polynomial dataArray
  42970. * from a cube map.
  42971. */
  42972. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  42973. function CubeMapToSphericalPolynomialTools() {
  42974. }
  42975. /**
  42976. * Converts a texture to the according Spherical Polynomial data.
  42977. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42978. *
  42979. * @param texture The texture to extract the information from.
  42980. * @return The Spherical Polynomial data.
  42981. */
  42982. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  42983. if (!texture.isCube) {
  42984. // Only supports cube Textures currently.
  42985. return null;
  42986. }
  42987. var size = texture.getSize().width;
  42988. var right = texture.readPixels(0);
  42989. var left = texture.readPixels(1);
  42990. var up;
  42991. var down;
  42992. if (texture.isRenderTarget) {
  42993. up = texture.readPixels(3);
  42994. down = texture.readPixels(2);
  42995. }
  42996. else {
  42997. up = texture.readPixels(2);
  42998. down = texture.readPixels(3);
  42999. }
  43000. var front = texture.readPixels(4);
  43001. var back = texture.readPixels(5);
  43002. var gammaSpace = texture.gammaSpace;
  43003. // Always read as RGBA.
  43004. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43005. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43006. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43007. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43008. }
  43009. var cubeInfo = {
  43010. size: size,
  43011. right: right,
  43012. left: left,
  43013. up: up,
  43014. down: down,
  43015. front: front,
  43016. back: back,
  43017. format: format,
  43018. type: type,
  43019. gammaSpace: gammaSpace,
  43020. };
  43021. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43022. };
  43023. /**
  43024. * Converts a cubemap to the according Spherical Polynomial data.
  43025. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43026. *
  43027. * @param cubeInfo The Cube map to extract the information from.
  43028. * @return The Spherical Polynomial data.
  43029. */
  43030. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43031. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43032. var totalSolidAngle = 0.0;
  43033. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43034. var du = 2.0 / cubeInfo.size;
  43035. var dv = du;
  43036. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43037. var minUV = du * 0.5 - 1.0;
  43038. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43039. var fileFace = this.FileFaces[faceIndex];
  43040. var dataArray = cubeInfo[fileFace.name];
  43041. var v = minUV;
  43042. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43043. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43044. // Because SP is still linear, so summation is fine in that basis.
  43045. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43046. for (var y = 0; y < cubeInfo.size; y++) {
  43047. var u = minUV;
  43048. for (var x = 0; x < cubeInfo.size; x++) {
  43049. // World direction (not normalised)
  43050. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43051. worldDirection.normalize();
  43052. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43053. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43054. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43055. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43056. // Handle Integer types.
  43057. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43058. r /= 255;
  43059. g /= 255;
  43060. b /= 255;
  43061. }
  43062. // Handle Gamma space textures.
  43063. if (cubeInfo.gammaSpace) {
  43064. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43065. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43066. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43067. }
  43068. var color = new BABYLON.Color3(r, g, b);
  43069. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43070. totalSolidAngle += deltaSolidAngle;
  43071. u += du;
  43072. }
  43073. v += dv;
  43074. }
  43075. }
  43076. // Solid angle for entire sphere is 4*pi
  43077. var sphereSolidAngle = 4.0 * Math.PI;
  43078. // Adjust the solid angle to allow for how many faces we processed.
  43079. var facesProcessed = 6.0;
  43080. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43081. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43082. // This is needed because the numerical integration over the cube uses a
  43083. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43084. // and also to compensate for accumulative error due to float precision in the summation.
  43085. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43086. sphericalHarmonics.scale(correctionFactor);
  43087. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43088. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43089. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43090. };
  43091. CubeMapToSphericalPolynomialTools.FileFaces = [
  43092. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43093. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43094. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43095. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43096. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43097. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43098. ];
  43099. return CubeMapToSphericalPolynomialTools;
  43100. }());
  43101. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43102. })(BABYLON || (BABYLON = {}));
  43103. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43104. var BABYLON;
  43105. (function (BABYLON) {
  43106. /**
  43107. * Manages the defines for the PBR Material.
  43108. * @hiddenChildren
  43109. */
  43110. var PBRMaterialDefines = /** @class */ (function (_super) {
  43111. __extends(PBRMaterialDefines, _super);
  43112. /**
  43113. * Initializes the PBR Material defines.
  43114. */
  43115. function PBRMaterialDefines() {
  43116. var _this = _super.call(this) || this;
  43117. _this.PBR = true;
  43118. _this.MAINUV1 = false;
  43119. _this.MAINUV2 = false;
  43120. _this.UV1 = false;
  43121. _this.UV2 = false;
  43122. _this.ALBEDO = false;
  43123. _this.ALBEDODIRECTUV = 0;
  43124. _this.VERTEXCOLOR = false;
  43125. _this.AMBIENT = false;
  43126. _this.AMBIENTDIRECTUV = 0;
  43127. _this.AMBIENTINGRAYSCALE = false;
  43128. _this.OPACITY = false;
  43129. _this.VERTEXALPHA = false;
  43130. _this.OPACITYDIRECTUV = 0;
  43131. _this.OPACITYRGB = false;
  43132. _this.ALPHATEST = false;
  43133. _this.DEPTHPREPASS = false;
  43134. _this.ALPHABLEND = false;
  43135. _this.ALPHAFROMALBEDO = false;
  43136. _this.ALPHATESTVALUE = "0.5";
  43137. _this.SPECULAROVERALPHA = false;
  43138. _this.RADIANCEOVERALPHA = false;
  43139. _this.ALPHAFRESNEL = false;
  43140. _this.LINEARALPHAFRESNEL = false;
  43141. _this.PREMULTIPLYALPHA = false;
  43142. _this.EMISSIVE = false;
  43143. _this.EMISSIVEDIRECTUV = 0;
  43144. _this.REFLECTIVITY = false;
  43145. _this.REFLECTIVITYDIRECTUV = 0;
  43146. _this.SPECULARTERM = false;
  43147. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43148. _this.MICROSURFACEAUTOMATIC = false;
  43149. _this.LODBASEDMICROSFURACE = false;
  43150. _this.MICROSURFACEMAP = false;
  43151. _this.MICROSURFACEMAPDIRECTUV = 0;
  43152. _this.METALLICWORKFLOW = false;
  43153. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43154. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43155. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43156. _this.AOSTOREINMETALMAPRED = false;
  43157. _this.ENVIRONMENTBRDF = false;
  43158. _this.NORMAL = false;
  43159. _this.TANGENT = false;
  43160. _this.BUMP = false;
  43161. _this.BUMPDIRECTUV = 0;
  43162. _this.OBJECTSPACE_NORMALMAP = false;
  43163. _this.PARALLAX = false;
  43164. _this.PARALLAXOCCLUSION = false;
  43165. _this.NORMALXYSCALE = true;
  43166. _this.LIGHTMAP = false;
  43167. _this.LIGHTMAPDIRECTUV = 0;
  43168. _this.USELIGHTMAPASSHADOWMAP = false;
  43169. _this.GAMMALIGHTMAP = false;
  43170. _this.REFLECTION = false;
  43171. _this.REFLECTIONMAP_3D = false;
  43172. _this.REFLECTIONMAP_SPHERICAL = false;
  43173. _this.REFLECTIONMAP_PLANAR = false;
  43174. _this.REFLECTIONMAP_CUBIC = false;
  43175. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43176. _this.REFLECTIONMAP_PROJECTION = false;
  43177. _this.REFLECTIONMAP_SKYBOX = false;
  43178. _this.REFLECTIONMAP_EXPLICIT = false;
  43179. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43180. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43181. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43182. _this.INVERTCUBICMAP = false;
  43183. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43184. _this.USESPHERICALINVERTEX = false;
  43185. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43186. _this.LODINREFLECTIONALPHA = false;
  43187. _this.GAMMAREFLECTION = false;
  43188. _this.RGBDREFLECTION = false;
  43189. _this.RADIANCEOCCLUSION = false;
  43190. _this.HORIZONOCCLUSION = false;
  43191. _this.REFRACTION = false;
  43192. _this.REFRACTIONMAP_3D = false;
  43193. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43194. _this.LODINREFRACTIONALPHA = false;
  43195. _this.GAMMAREFRACTION = false;
  43196. _this.RGBDREFRACTION = false;
  43197. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43198. _this.INSTANCES = false;
  43199. _this.NUM_BONE_INFLUENCERS = 0;
  43200. _this.BonesPerMesh = 0;
  43201. _this.NONUNIFORMSCALING = false;
  43202. _this.MORPHTARGETS = false;
  43203. _this.MORPHTARGETS_NORMAL = false;
  43204. _this.MORPHTARGETS_TANGENT = false;
  43205. _this.NUM_MORPH_INFLUENCERS = 0;
  43206. _this.IMAGEPROCESSING = false;
  43207. _this.VIGNETTE = false;
  43208. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43209. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43210. _this.TONEMAPPING = false;
  43211. _this.CONTRAST = false;
  43212. _this.COLORCURVES = false;
  43213. _this.COLORGRADING = false;
  43214. _this.COLORGRADING3D = false;
  43215. _this.SAMPLER3DGREENDEPTH = false;
  43216. _this.SAMPLER3DBGRMAP = false;
  43217. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43218. _this.EXPOSURE = false;
  43219. _this.USEPHYSICALLIGHTFALLOFF = false;
  43220. _this.TWOSIDEDLIGHTING = false;
  43221. _this.SHADOWFLOAT = false;
  43222. _this.CLIPPLANE = false;
  43223. _this.POINTSIZE = false;
  43224. _this.FOG = false;
  43225. _this.LOGARITHMICDEPTH = false;
  43226. _this.FORCENORMALFORWARD = false;
  43227. _this.SPECULARAA = false;
  43228. _this.UNLIT = false;
  43229. _this.rebuild();
  43230. return _this;
  43231. }
  43232. /**
  43233. * Resets the PBR Material defines.
  43234. */
  43235. PBRMaterialDefines.prototype.reset = function () {
  43236. _super.prototype.reset.call(this);
  43237. this.ALPHATESTVALUE = "0.5";
  43238. this.PBR = true;
  43239. };
  43240. return PBRMaterialDefines;
  43241. }(BABYLON.MaterialDefines));
  43242. /**
  43243. * The Physically based material base class of BJS.
  43244. *
  43245. * This offers the main features of a standard PBR material.
  43246. * For more information, please refer to the documentation :
  43247. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43248. */
  43249. var PBRBaseMaterial = /** @class */ (function (_super) {
  43250. __extends(PBRBaseMaterial, _super);
  43251. /**
  43252. * Instantiates a new PBRMaterial instance.
  43253. *
  43254. * @param name The material name
  43255. * @param scene The scene the material will be use in.
  43256. */
  43257. function PBRBaseMaterial(name, scene) {
  43258. var _this = _super.call(this, name, scene) || this;
  43259. /**
  43260. * Intensity of the direct lights e.g. the four lights available in your scene.
  43261. * This impacts both the direct diffuse and specular highlights.
  43262. */
  43263. _this._directIntensity = 1.0;
  43264. /**
  43265. * Intensity of the emissive part of the material.
  43266. * This helps controlling the emissive effect without modifying the emissive color.
  43267. */
  43268. _this._emissiveIntensity = 1.0;
  43269. /**
  43270. * Intensity of the environment e.g. how much the environment will light the object
  43271. * either through harmonics for rough material or through the refelction for shiny ones.
  43272. */
  43273. _this._environmentIntensity = 1.0;
  43274. /**
  43275. * This is a special control allowing the reduction of the specular highlights coming from the
  43276. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43277. */
  43278. _this._specularIntensity = 1.0;
  43279. /**
  43280. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43281. */
  43282. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43283. /**
  43284. * Debug Control allowing disabling the bump map on this material.
  43285. */
  43286. _this._disableBumpMap = false;
  43287. /**
  43288. * AKA Occlusion Texture Intensity in other nomenclature.
  43289. */
  43290. _this._ambientTextureStrength = 1.0;
  43291. /**
  43292. * The color of a material in ambient lighting.
  43293. */
  43294. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43295. /**
  43296. * AKA Diffuse Color in other nomenclature.
  43297. */
  43298. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43299. /**
  43300. * AKA Specular Color in other nomenclature.
  43301. */
  43302. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43303. /**
  43304. * The color applied when light is reflected from a material.
  43305. */
  43306. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43307. /**
  43308. * The color applied when light is emitted from a material.
  43309. */
  43310. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43311. /**
  43312. * AKA Glossiness in other nomenclature.
  43313. */
  43314. _this._microSurface = 0.9;
  43315. /**
  43316. * source material index of refraction (IOR)' / 'destination material IOR.
  43317. */
  43318. _this._indexOfRefraction = 0.66;
  43319. /**
  43320. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43321. */
  43322. _this._invertRefractionY = false;
  43323. /**
  43324. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43325. * Materials half opaque for instance using refraction could benefit from this control.
  43326. */
  43327. _this._linkRefractionWithTransparency = false;
  43328. /**
  43329. * Specifies that the material will use the light map as a show map.
  43330. */
  43331. _this._useLightmapAsShadowmap = false;
  43332. /**
  43333. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43334. * makes the reflect vector face the model (under horizon).
  43335. */
  43336. _this._useHorizonOcclusion = true;
  43337. /**
  43338. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43339. * too much the area relying on ambient texture to define their ambient occlusion.
  43340. */
  43341. _this._useRadianceOcclusion = true;
  43342. /**
  43343. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43344. */
  43345. _this._useAlphaFromAlbedoTexture = false;
  43346. /**
  43347. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43348. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43349. */
  43350. _this._useSpecularOverAlpha = true;
  43351. /**
  43352. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43353. */
  43354. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43355. /**
  43356. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43357. */
  43358. _this._useRoughnessFromMetallicTextureAlpha = true;
  43359. /**
  43360. * Specifies if the metallic texture contains the roughness information in its green channel.
  43361. */
  43362. _this._useRoughnessFromMetallicTextureGreen = false;
  43363. /**
  43364. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43365. */
  43366. _this._useMetallnessFromMetallicTextureBlue = false;
  43367. /**
  43368. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43369. */
  43370. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43371. /**
  43372. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43373. */
  43374. _this._useAmbientInGrayScale = false;
  43375. /**
  43376. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43377. * The material will try to infer what glossiness each pixel should be.
  43378. */
  43379. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43380. /**
  43381. * BJS is using an harcoded light falloff based on a manually sets up range.
  43382. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43383. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43384. */
  43385. _this._usePhysicalLightFalloff = true;
  43386. /**
  43387. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43388. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43389. */
  43390. _this._useRadianceOverAlpha = true;
  43391. /**
  43392. * Allows using an object space normal map (instead of tangent space).
  43393. */
  43394. _this._useObjectSpaceNormalMap = false;
  43395. /**
  43396. * Allows using the bump map in parallax mode.
  43397. */
  43398. _this._useParallax = false;
  43399. /**
  43400. * Allows using the bump map in parallax occlusion mode.
  43401. */
  43402. _this._useParallaxOcclusion = false;
  43403. /**
  43404. * Controls the scale bias of the parallax mode.
  43405. */
  43406. _this._parallaxScaleBias = 0.05;
  43407. /**
  43408. * If sets to true, disables all the lights affecting the material.
  43409. */
  43410. _this._disableLighting = false;
  43411. /**
  43412. * Number of Simultaneous lights allowed on the material.
  43413. */
  43414. _this._maxSimultaneousLights = 4;
  43415. /**
  43416. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43417. */
  43418. _this._invertNormalMapX = false;
  43419. /**
  43420. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43421. */
  43422. _this._invertNormalMapY = false;
  43423. /**
  43424. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43425. */
  43426. _this._twoSidedLighting = false;
  43427. /**
  43428. * Defines the alpha limits in alpha test mode.
  43429. */
  43430. _this._alphaCutOff = 0.4;
  43431. /**
  43432. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43433. */
  43434. _this._forceAlphaTest = false;
  43435. /**
  43436. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43437. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43438. */
  43439. _this._useAlphaFresnel = false;
  43440. /**
  43441. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43442. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43443. */
  43444. _this._useLinearAlphaFresnel = false;
  43445. /**
  43446. * The transparency mode of the material.
  43447. */
  43448. _this._transparencyMode = null;
  43449. /**
  43450. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43451. * from cos thetav and roughness:
  43452. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43453. */
  43454. _this._environmentBRDFTexture = null;
  43455. /**
  43456. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43457. */
  43458. _this._forceIrradianceInFragment = false;
  43459. /**
  43460. * Force normal to face away from face.
  43461. */
  43462. _this._forceNormalForward = false;
  43463. /**
  43464. * Enables specular anti aliasing in the PBR shader.
  43465. * It will both interacts on the Geometry for analytical and IBL lighting.
  43466. * It also prefilter the roughness map based on the bump values.
  43467. */
  43468. _this._enableSpecularAntiAliasing = false;
  43469. /**
  43470. * Stores the available render targets.
  43471. */
  43472. _this._renderTargets = new BABYLON.SmartArray(16);
  43473. /**
  43474. * Sets the global ambient color for the material used in lighting calculations.
  43475. */
  43476. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43477. /**
  43478. * If set to true, no lighting calculations will be applied.
  43479. */
  43480. _this._unlit = false;
  43481. // Setup the default processing configuration to the scene.
  43482. _this._attachImageProcessingConfiguration(null);
  43483. _this.getRenderTargetTextures = function () {
  43484. _this._renderTargets.reset();
  43485. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43486. _this._renderTargets.push(_this._reflectionTexture);
  43487. }
  43488. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43489. _this._renderTargets.push(_this._refractionTexture);
  43490. }
  43491. return _this._renderTargets;
  43492. };
  43493. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43494. return _this;
  43495. }
  43496. /**
  43497. * Attaches a new image processing configuration to the PBR Material.
  43498. * @param configuration
  43499. */
  43500. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43501. var _this = this;
  43502. if (configuration === this._imageProcessingConfiguration) {
  43503. return;
  43504. }
  43505. // Detaches observer.
  43506. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43507. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43508. }
  43509. // Pick the scene configuration if needed.
  43510. if (!configuration) {
  43511. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43512. }
  43513. else {
  43514. this._imageProcessingConfiguration = configuration;
  43515. }
  43516. // Attaches observer.
  43517. if (this._imageProcessingConfiguration) {
  43518. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43519. _this._markAllSubMeshesAsImageProcessingDirty();
  43520. });
  43521. }
  43522. };
  43523. /**
  43524. * Gets the name of the material class.
  43525. */
  43526. PBRBaseMaterial.prototype.getClassName = function () {
  43527. return "PBRBaseMaterial";
  43528. };
  43529. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43530. /**
  43531. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43532. */
  43533. get: function () {
  43534. return this._useLogarithmicDepth;
  43535. },
  43536. /**
  43537. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43538. */
  43539. set: function (value) {
  43540. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43541. },
  43542. enumerable: true,
  43543. configurable: true
  43544. });
  43545. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43546. /**
  43547. * Gets the current transparency mode.
  43548. */
  43549. get: function () {
  43550. return this._transparencyMode;
  43551. },
  43552. /**
  43553. * Sets the transparency mode of the material.
  43554. *
  43555. * | Value | Type | Description |
  43556. * | ----- | ----------------------------------- | ----------- |
  43557. * | 0 | OPAQUE | |
  43558. * | 1 | ALPHATEST | |
  43559. * | 2 | ALPHABLEND | |
  43560. * | 3 | ALPHATESTANDBLEND | |
  43561. *
  43562. */
  43563. set: function (value) {
  43564. if (this._transparencyMode === value) {
  43565. return;
  43566. }
  43567. this._transparencyMode = value;
  43568. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43569. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43570. },
  43571. enumerable: true,
  43572. configurable: true
  43573. });
  43574. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43575. /**
  43576. * Returns true if alpha blending should be disabled.
  43577. */
  43578. get: function () {
  43579. return (this._linkRefractionWithTransparency ||
  43580. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43581. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43582. },
  43583. enumerable: true,
  43584. configurable: true
  43585. });
  43586. /**
  43587. * Specifies whether or not this material should be rendered in alpha blend mode.
  43588. */
  43589. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43590. if (this._disableAlphaBlending) {
  43591. return false;
  43592. }
  43593. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43594. };
  43595. /**
  43596. * Specifies if the mesh will require alpha blending.
  43597. * @param mesh - BJS mesh.
  43598. */
  43599. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43600. if (this._disableAlphaBlending) {
  43601. return false;
  43602. }
  43603. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43604. };
  43605. /**
  43606. * Specifies whether or not this material should be rendered in alpha test mode.
  43607. */
  43608. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43609. if (this._forceAlphaTest) {
  43610. return true;
  43611. }
  43612. if (this._linkRefractionWithTransparency) {
  43613. return false;
  43614. }
  43615. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43616. };
  43617. /**
  43618. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43619. */
  43620. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43621. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43622. };
  43623. /**
  43624. * Gets the texture used for the alpha test.
  43625. */
  43626. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43627. return this._albedoTexture;
  43628. };
  43629. /**
  43630. * Specifies that the submesh is ready to be used.
  43631. * @param mesh - BJS mesh.
  43632. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43633. * @param useInstances - Specifies that instances should be used.
  43634. * @returns - boolean indicating that the submesh is ready or not.
  43635. */
  43636. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43637. if (subMesh.effect && this.isFrozen) {
  43638. if (this._wasPreviouslyReady) {
  43639. return true;
  43640. }
  43641. }
  43642. if (!subMesh._materialDefines) {
  43643. subMesh._materialDefines = new PBRMaterialDefines();
  43644. }
  43645. var defines = subMesh._materialDefines;
  43646. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43647. if (defines._renderId === this.getScene().getRenderId()) {
  43648. return true;
  43649. }
  43650. }
  43651. var scene = this.getScene();
  43652. var engine = scene.getEngine();
  43653. if (defines._areTexturesDirty) {
  43654. if (scene.texturesEnabled) {
  43655. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43656. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43657. return false;
  43658. }
  43659. }
  43660. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43661. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43662. return false;
  43663. }
  43664. }
  43665. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43666. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43667. return false;
  43668. }
  43669. }
  43670. var reflectionTexture = this._getReflectionTexture();
  43671. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43672. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43673. return false;
  43674. }
  43675. }
  43676. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43677. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43678. return false;
  43679. }
  43680. }
  43681. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43682. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43683. return false;
  43684. }
  43685. }
  43686. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43687. if (this._metallicTexture) {
  43688. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43689. return false;
  43690. }
  43691. }
  43692. else if (this._reflectivityTexture) {
  43693. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43694. return false;
  43695. }
  43696. }
  43697. if (this._microSurfaceTexture) {
  43698. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43699. return false;
  43700. }
  43701. }
  43702. }
  43703. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43704. // Bump texture cannot be not blocking.
  43705. if (!this._bumpTexture.isReady()) {
  43706. return false;
  43707. }
  43708. }
  43709. var refractionTexture = this._getRefractionTexture();
  43710. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43711. if (!refractionTexture.isReadyOrNotBlocking()) {
  43712. return false;
  43713. }
  43714. }
  43715. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43716. // This is blocking.
  43717. if (!this._environmentBRDFTexture.isReady()) {
  43718. return false;
  43719. }
  43720. }
  43721. }
  43722. }
  43723. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43724. if (!this._imageProcessingConfiguration.isReady()) {
  43725. return false;
  43726. }
  43727. }
  43728. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43729. mesh.createNormals(true);
  43730. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43731. }
  43732. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43733. if (effect) {
  43734. scene.resetCachedMaterial();
  43735. subMesh.setEffect(effect, defines);
  43736. this.buildUniformLayout();
  43737. }
  43738. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43739. return false;
  43740. }
  43741. defines._renderId = scene.getRenderId();
  43742. this._wasPreviouslyReady = true;
  43743. return true;
  43744. };
  43745. /**
  43746. * Specifies if the material uses metallic roughness workflow.
  43747. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43748. */
  43749. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43750. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43751. return true;
  43752. }
  43753. return false;
  43754. };
  43755. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43756. if (onCompiled === void 0) { onCompiled = null; }
  43757. if (onError === void 0) { onError = null; }
  43758. if (useInstances === void 0) { useInstances = null; }
  43759. if (useClipPlane === void 0) { useClipPlane = null; }
  43760. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43761. if (!defines.isDirty) {
  43762. return null;
  43763. }
  43764. defines.markAsProcessed();
  43765. var scene = this.getScene();
  43766. var engine = scene.getEngine();
  43767. // Fallbacks
  43768. var fallbacks = new BABYLON.EffectFallbacks();
  43769. var fallbackRank = 0;
  43770. if (defines.USESPHERICALINVERTEX) {
  43771. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43772. }
  43773. if (defines.FOG) {
  43774. fallbacks.addFallback(fallbackRank, "FOG");
  43775. }
  43776. if (defines.SPECULARAA) {
  43777. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43778. }
  43779. if (defines.POINTSIZE) {
  43780. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43781. }
  43782. if (defines.LOGARITHMICDEPTH) {
  43783. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43784. }
  43785. if (defines.PARALLAX) {
  43786. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43787. }
  43788. if (defines.PARALLAXOCCLUSION) {
  43789. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43790. }
  43791. if (defines.ENVIRONMENTBRDF) {
  43792. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43793. }
  43794. if (defines.TANGENT) {
  43795. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43796. }
  43797. if (defines.BUMP) {
  43798. fallbacks.addFallback(fallbackRank++, "BUMP");
  43799. }
  43800. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43801. if (defines.SPECULARTERM) {
  43802. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43803. }
  43804. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43805. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43806. }
  43807. if (defines.LIGHTMAP) {
  43808. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43809. }
  43810. if (defines.NORMAL) {
  43811. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43812. }
  43813. if (defines.AMBIENT) {
  43814. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43815. }
  43816. if (defines.EMISSIVE) {
  43817. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43818. }
  43819. if (defines.VERTEXCOLOR) {
  43820. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43821. }
  43822. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43823. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43824. }
  43825. if (defines.MORPHTARGETS) {
  43826. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43827. }
  43828. //Attributes
  43829. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43830. if (defines.NORMAL) {
  43831. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43832. }
  43833. if (defines.TANGENT) {
  43834. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43835. }
  43836. if (defines.UV1) {
  43837. attribs.push(BABYLON.VertexBuffer.UVKind);
  43838. }
  43839. if (defines.UV2) {
  43840. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43841. }
  43842. if (defines.VERTEXCOLOR) {
  43843. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43844. }
  43845. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43846. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43847. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43848. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43849. "vFogInfos", "vFogColor", "pointSize",
  43850. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43851. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43852. "mBones",
  43853. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43854. "vLightingIntensity",
  43855. "logarithmicDepthConstant",
  43856. "vSphericalX", "vSphericalY", "vSphericalZ",
  43857. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43858. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43859. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43860. "vTangentSpaceParams"
  43861. ];
  43862. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43863. "bumpSampler", "lightmapSampler", "opacitySampler",
  43864. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43865. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43866. "microSurfaceSampler", "environmentBrdfSampler"];
  43867. var uniformBuffers = ["Material", "Scene"];
  43868. if (BABYLON.ImageProcessingConfiguration) {
  43869. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43870. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43871. }
  43872. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43873. uniformsNames: uniforms,
  43874. uniformBuffersNames: uniformBuffers,
  43875. samplers: samplers,
  43876. defines: defines,
  43877. maxSimultaneousLights: this._maxSimultaneousLights
  43878. });
  43879. var join = defines.toString();
  43880. return engine.createEffect("pbr", {
  43881. attributes: attribs,
  43882. uniformsNames: uniforms,
  43883. uniformBuffersNames: uniformBuffers,
  43884. samplers: samplers,
  43885. defines: join,
  43886. fallbacks: fallbacks,
  43887. onCompiled: onCompiled,
  43888. onError: onError,
  43889. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43890. }, engine);
  43891. };
  43892. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43893. if (useInstances === void 0) { useInstances = null; }
  43894. if (useClipPlane === void 0) { useClipPlane = null; }
  43895. var scene = this.getScene();
  43896. var engine = scene.getEngine();
  43897. // Lights
  43898. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43899. defines._needNormals = true;
  43900. // Textures
  43901. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43902. if (defines._areTexturesDirty) {
  43903. defines._needUVs = false;
  43904. if (scene.texturesEnabled) {
  43905. if (scene.getEngine().getCaps().textureLOD) {
  43906. defines.LODBASEDMICROSFURACE = true;
  43907. }
  43908. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43909. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43910. }
  43911. else {
  43912. defines.ALBEDO = false;
  43913. }
  43914. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43915. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43916. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43917. }
  43918. else {
  43919. defines.AMBIENT = false;
  43920. }
  43921. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43922. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43923. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43924. }
  43925. else {
  43926. defines.OPACITY = false;
  43927. }
  43928. var reflectionTexture = this._getReflectionTexture();
  43929. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43930. defines.REFLECTION = true;
  43931. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43932. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43933. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43934. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43935. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43936. defines.INVERTCUBICMAP = true;
  43937. }
  43938. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43939. switch (reflectionTexture.coordinatesMode) {
  43940. case BABYLON.Texture.EXPLICIT_MODE:
  43941. defines.REFLECTIONMAP_EXPLICIT = true;
  43942. break;
  43943. case BABYLON.Texture.PLANAR_MODE:
  43944. defines.REFLECTIONMAP_PLANAR = true;
  43945. break;
  43946. case BABYLON.Texture.PROJECTION_MODE:
  43947. defines.REFLECTIONMAP_PROJECTION = true;
  43948. break;
  43949. case BABYLON.Texture.SKYBOX_MODE:
  43950. defines.REFLECTIONMAP_SKYBOX = true;
  43951. break;
  43952. case BABYLON.Texture.SPHERICAL_MODE:
  43953. defines.REFLECTIONMAP_SPHERICAL = true;
  43954. break;
  43955. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43956. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43957. break;
  43958. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43959. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43960. break;
  43961. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43962. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43963. break;
  43964. case BABYLON.Texture.CUBIC_MODE:
  43965. case BABYLON.Texture.INVCUBIC_MODE:
  43966. default:
  43967. defines.REFLECTIONMAP_CUBIC = true;
  43968. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43969. break;
  43970. }
  43971. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43972. if (reflectionTexture.sphericalPolynomial) {
  43973. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43974. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43975. defines.USESPHERICALINVERTEX = false;
  43976. }
  43977. else {
  43978. defines.USESPHERICALINVERTEX = true;
  43979. }
  43980. }
  43981. }
  43982. }
  43983. else {
  43984. defines.REFLECTION = false;
  43985. defines.REFLECTIONMAP_3D = false;
  43986. defines.REFLECTIONMAP_SPHERICAL = false;
  43987. defines.REFLECTIONMAP_PLANAR = false;
  43988. defines.REFLECTIONMAP_CUBIC = false;
  43989. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43990. defines.REFLECTIONMAP_PROJECTION = false;
  43991. defines.REFLECTIONMAP_SKYBOX = false;
  43992. defines.REFLECTIONMAP_EXPLICIT = false;
  43993. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43994. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43995. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43996. defines.INVERTCUBICMAP = false;
  43997. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43998. defines.USESPHERICALINVERTEX = false;
  43999. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44000. defines.LODINREFLECTIONALPHA = false;
  44001. defines.GAMMAREFLECTION = false;
  44002. defines.RGBDREFLECTION = false;
  44003. }
  44004. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44005. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44006. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44007. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44008. }
  44009. else {
  44010. defines.LIGHTMAP = false;
  44011. }
  44012. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44013. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44014. }
  44015. else {
  44016. defines.EMISSIVE = false;
  44017. }
  44018. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44019. if (this._metallicTexture) {
  44020. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44021. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44022. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44023. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44024. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44025. }
  44026. else if (this._reflectivityTexture) {
  44027. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44028. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44029. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44030. }
  44031. else {
  44032. defines.REFLECTIVITY = false;
  44033. }
  44034. if (this._microSurfaceTexture) {
  44035. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44036. }
  44037. else {
  44038. defines.MICROSURFACEMAP = false;
  44039. }
  44040. }
  44041. else {
  44042. defines.REFLECTIVITY = false;
  44043. defines.MICROSURFACEMAP = false;
  44044. }
  44045. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44046. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44047. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44048. defines.PARALLAX = true;
  44049. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44050. }
  44051. else {
  44052. defines.PARALLAX = false;
  44053. }
  44054. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44055. }
  44056. else {
  44057. defines.BUMP = false;
  44058. }
  44059. var refractionTexture = this._getRefractionTexture();
  44060. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44061. defines.REFRACTION = true;
  44062. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44063. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44064. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44065. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44066. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44067. if (this._linkRefractionWithTransparency) {
  44068. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44069. }
  44070. }
  44071. else {
  44072. defines.REFRACTION = false;
  44073. }
  44074. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44075. defines.ENVIRONMENTBRDF = true;
  44076. }
  44077. else {
  44078. defines.ENVIRONMENTBRDF = false;
  44079. }
  44080. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44081. defines.ALPHAFROMALBEDO = true;
  44082. }
  44083. else {
  44084. defines.ALPHAFROMALBEDO = false;
  44085. }
  44086. }
  44087. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44088. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44089. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44090. if (!this.backFaceCulling && this._twoSidedLighting) {
  44091. defines.TWOSIDEDLIGHTING = true;
  44092. }
  44093. else {
  44094. defines.TWOSIDEDLIGHTING = false;
  44095. }
  44096. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44097. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44098. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44099. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44100. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44101. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44102. }
  44103. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44104. this._imageProcessingConfiguration.prepareDefines(defines);
  44105. }
  44106. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44107. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44108. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44109. // Misc.
  44110. if (defines._areMiscDirty) {
  44111. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44112. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44113. }
  44114. // Values that need to be evaluated on every frame
  44115. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44116. // Attribs
  44117. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44118. };
  44119. /**
  44120. * Force shader compilation
  44121. */
  44122. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44123. var _this = this;
  44124. var localOptions = __assign({ clipPlane: false }, options);
  44125. var defines = new PBRMaterialDefines();
  44126. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44127. if (effect.isReady()) {
  44128. if (onCompiled) {
  44129. onCompiled(this);
  44130. }
  44131. }
  44132. else {
  44133. effect.onCompileObservable.add(function () {
  44134. if (onCompiled) {
  44135. onCompiled(_this);
  44136. }
  44137. });
  44138. }
  44139. };
  44140. /**
  44141. * Initializes the uniform buffer layout for the shader.
  44142. */
  44143. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44144. // Order is important !
  44145. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44146. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44147. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44148. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44149. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44150. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44151. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44152. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44153. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44154. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44155. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44156. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44157. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44158. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44159. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44160. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44161. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44162. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44163. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44164. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44165. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44166. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44167. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44168. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44169. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44170. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44171. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44172. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44173. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44174. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44175. this._uniformBuffer.addUniform("pointSize", 1);
  44176. this._uniformBuffer.create();
  44177. };
  44178. /**
  44179. * Unbinds the textures.
  44180. */
  44181. PBRBaseMaterial.prototype.unbind = function () {
  44182. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44183. this._uniformBuffer.setTexture("reflectionSampler", null);
  44184. }
  44185. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44186. this._uniformBuffer.setTexture("refractionSampler", null);
  44187. }
  44188. _super.prototype.unbind.call(this);
  44189. };
  44190. /**
  44191. * Binds the submesh data.
  44192. * @param world - The world matrix.
  44193. * @param mesh - The BJS mesh.
  44194. * @param subMesh - A submesh of the BJS mesh.
  44195. */
  44196. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44197. var scene = this.getScene();
  44198. var defines = subMesh._materialDefines;
  44199. if (!defines) {
  44200. return;
  44201. }
  44202. var effect = subMesh.effect;
  44203. if (!effect) {
  44204. return;
  44205. }
  44206. this._activeEffect = effect;
  44207. // Matrices
  44208. this.bindOnlyWorldMatrix(world);
  44209. // Normal Matrix
  44210. if (defines.OBJECTSPACE_NORMALMAP) {
  44211. world.toNormalMatrix(this._normalMatrix);
  44212. this.bindOnlyNormalMatrix(this._normalMatrix);
  44213. }
  44214. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44215. // Bones
  44216. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44217. var reflectionTexture = null;
  44218. if (mustRebind) {
  44219. this._uniformBuffer.bindToEffect(effect, "Material");
  44220. this.bindViewProjection(effect);
  44221. reflectionTexture = this._getReflectionTexture();
  44222. var refractionTexture = this._getRefractionTexture();
  44223. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44224. // Texture uniforms
  44225. if (scene.texturesEnabled) {
  44226. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44227. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44228. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44229. }
  44230. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44231. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44232. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44233. }
  44234. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44235. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44236. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44237. }
  44238. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44239. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44240. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44241. if (reflectionTexture.boundingBoxSize) {
  44242. var cubeTexture = reflectionTexture;
  44243. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44244. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44245. }
  44246. var polynomials = reflectionTexture.sphericalPolynomial;
  44247. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44248. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44249. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44250. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44251. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44252. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44253. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44254. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44255. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44256. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44257. }
  44258. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44259. }
  44260. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44261. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44262. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44263. }
  44264. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44265. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44266. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44267. }
  44268. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44269. if (this._metallicTexture) {
  44270. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44271. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44272. }
  44273. else if (this._reflectivityTexture) {
  44274. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44275. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44276. }
  44277. if (this._microSurfaceTexture) {
  44278. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44279. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44280. }
  44281. }
  44282. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44283. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44284. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44285. if (scene._mirroredCameraPosition) {
  44286. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44287. }
  44288. else {
  44289. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44290. }
  44291. }
  44292. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44293. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44294. var depth = 1.0;
  44295. if (!refractionTexture.isCube) {
  44296. if (refractionTexture.depth) {
  44297. depth = refractionTexture.depth;
  44298. }
  44299. }
  44300. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44301. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44302. }
  44303. }
  44304. // Point size
  44305. if (this.pointsCloud) {
  44306. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44307. }
  44308. // Colors
  44309. if (defines.METALLICWORKFLOW) {
  44310. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44311. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44312. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44313. }
  44314. else {
  44315. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44316. }
  44317. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44318. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44319. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44320. // Misc
  44321. this._lightingInfos.x = this._directIntensity;
  44322. this._lightingInfos.y = this._emissiveIntensity;
  44323. this._lightingInfos.z = this._environmentIntensity;
  44324. this._lightingInfos.w = this._specularIntensity;
  44325. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44326. }
  44327. // Textures
  44328. if (scene.texturesEnabled) {
  44329. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44330. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44331. }
  44332. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44333. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44334. }
  44335. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44336. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44337. }
  44338. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44339. if (defines.LODBASEDMICROSFURACE) {
  44340. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44341. }
  44342. else {
  44343. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44344. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44345. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44346. }
  44347. }
  44348. if (defines.ENVIRONMENTBRDF) {
  44349. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44350. }
  44351. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44352. if (defines.LODBASEDMICROSFURACE) {
  44353. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44354. }
  44355. else {
  44356. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44357. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44358. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44359. }
  44360. }
  44361. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44362. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44363. }
  44364. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44365. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44366. }
  44367. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44368. if (this._metallicTexture) {
  44369. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44370. }
  44371. else if (this._reflectivityTexture) {
  44372. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44373. }
  44374. if (this._microSurfaceTexture) {
  44375. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44376. }
  44377. }
  44378. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44379. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44380. }
  44381. }
  44382. // Clip plane
  44383. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44384. // Colors
  44385. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44386. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44387. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44388. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44389. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44390. }
  44391. if (mustRebind || !this.isFrozen) {
  44392. // Lights
  44393. if (scene.lightsEnabled && !this._disableLighting) {
  44394. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44395. }
  44396. // View
  44397. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44398. this.bindView(effect);
  44399. }
  44400. // Fog
  44401. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44402. // Morph targets
  44403. if (defines.NUM_MORPH_INFLUENCERS) {
  44404. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44405. }
  44406. // image processing
  44407. this._imageProcessingConfiguration.bind(this._activeEffect);
  44408. // Log. depth
  44409. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44410. }
  44411. this._uniformBuffer.update();
  44412. this._afterBind(mesh, this._activeEffect);
  44413. };
  44414. /**
  44415. * Returns the animatable textures.
  44416. * @returns - Array of animatable textures.
  44417. */
  44418. PBRBaseMaterial.prototype.getAnimatables = function () {
  44419. var results = [];
  44420. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44421. results.push(this._albedoTexture);
  44422. }
  44423. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44424. results.push(this._ambientTexture);
  44425. }
  44426. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44427. results.push(this._opacityTexture);
  44428. }
  44429. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44430. results.push(this._reflectionTexture);
  44431. }
  44432. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44433. results.push(this._emissiveTexture);
  44434. }
  44435. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44436. results.push(this._metallicTexture);
  44437. }
  44438. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44439. results.push(this._reflectivityTexture);
  44440. }
  44441. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44442. results.push(this._bumpTexture);
  44443. }
  44444. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44445. results.push(this._lightmapTexture);
  44446. }
  44447. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44448. results.push(this._refractionTexture);
  44449. }
  44450. return results;
  44451. };
  44452. /**
  44453. * Returns the texture used for reflections.
  44454. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44455. */
  44456. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44457. if (this._reflectionTexture) {
  44458. return this._reflectionTexture;
  44459. }
  44460. return this.getScene().environmentTexture;
  44461. };
  44462. /**
  44463. * Returns the texture used for refraction or null if none is used.
  44464. * @returns - Refection texture if present. If no refraction texture and refraction
  44465. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44466. */
  44467. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44468. if (this._refractionTexture) {
  44469. return this._refractionTexture;
  44470. }
  44471. if (this._linkRefractionWithTransparency) {
  44472. return this.getScene().environmentTexture;
  44473. }
  44474. return null;
  44475. };
  44476. /**
  44477. * Disposes the resources of the material.
  44478. * @param forceDisposeEffect - Forces the disposal of effects.
  44479. * @param forceDisposeTextures - Forces the disposal of all textures.
  44480. */
  44481. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44482. if (forceDisposeTextures) {
  44483. if (this._albedoTexture) {
  44484. this._albedoTexture.dispose();
  44485. }
  44486. if (this._ambientTexture) {
  44487. this._ambientTexture.dispose();
  44488. }
  44489. if (this._opacityTexture) {
  44490. this._opacityTexture.dispose();
  44491. }
  44492. if (this._reflectionTexture) {
  44493. this._reflectionTexture.dispose();
  44494. }
  44495. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44496. this._environmentBRDFTexture.dispose();
  44497. }
  44498. if (this._emissiveTexture) {
  44499. this._emissiveTexture.dispose();
  44500. }
  44501. if (this._metallicTexture) {
  44502. this._metallicTexture.dispose();
  44503. }
  44504. if (this._reflectivityTexture) {
  44505. this._reflectivityTexture.dispose();
  44506. }
  44507. if (this._bumpTexture) {
  44508. this._bumpTexture.dispose();
  44509. }
  44510. if (this._lightmapTexture) {
  44511. this._lightmapTexture.dispose();
  44512. }
  44513. if (this._refractionTexture) {
  44514. this._refractionTexture.dispose();
  44515. }
  44516. }
  44517. this._renderTargets.dispose();
  44518. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44519. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44520. }
  44521. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44522. };
  44523. /**
  44524. * Stores the reflectivity values based on metallic roughness workflow.
  44525. */
  44526. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44527. __decorate([
  44528. BABYLON.serializeAsImageProcessingConfiguration()
  44529. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44530. __decorate([
  44531. BABYLON.serialize()
  44532. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44533. __decorate([
  44534. BABYLON.serialize()
  44535. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44536. return PBRBaseMaterial;
  44537. }(BABYLON.PushMaterial));
  44538. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44539. })(BABYLON || (BABYLON = {}));
  44540. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44541. var BABYLON;
  44542. (function (BABYLON) {
  44543. /**
  44544. * The Physically based simple base material of BJS.
  44545. *
  44546. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44547. * It is used as the base class for both the specGloss and metalRough conventions.
  44548. */
  44549. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44550. __extends(PBRBaseSimpleMaterial, _super);
  44551. /**
  44552. * Instantiates a new PBRMaterial instance.
  44553. *
  44554. * @param name The material name
  44555. * @param scene The scene the material will be use in.
  44556. */
  44557. function PBRBaseSimpleMaterial(name, scene) {
  44558. var _this = _super.call(this, name, scene) || this;
  44559. /**
  44560. * Number of Simultaneous lights allowed on the material.
  44561. */
  44562. _this.maxSimultaneousLights = 4;
  44563. /**
  44564. * If sets to true, disables all the lights affecting the material.
  44565. */
  44566. _this.disableLighting = false;
  44567. /**
  44568. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44569. */
  44570. _this.invertNormalMapX = false;
  44571. /**
  44572. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44573. */
  44574. _this.invertNormalMapY = false;
  44575. /**
  44576. * Emissivie color used to self-illuminate the model.
  44577. */
  44578. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44579. /**
  44580. * Occlusion Channel Strenght.
  44581. */
  44582. _this.occlusionStrength = 1.0;
  44583. _this.useLightmapAsShadowmap = false;
  44584. _this._useAlphaFromAlbedoTexture = true;
  44585. _this._useAmbientInGrayScale = true;
  44586. return _this;
  44587. }
  44588. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44589. /**
  44590. * Gets the current double sided mode.
  44591. */
  44592. get: function () {
  44593. return this._twoSidedLighting;
  44594. },
  44595. /**
  44596. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44597. */
  44598. set: function (value) {
  44599. if (this._twoSidedLighting === value) {
  44600. return;
  44601. }
  44602. this._twoSidedLighting = value;
  44603. this.backFaceCulling = !value;
  44604. this._markAllSubMeshesAsTexturesDirty();
  44605. },
  44606. enumerable: true,
  44607. configurable: true
  44608. });
  44609. /**
  44610. * Return the active textures of the material.
  44611. */
  44612. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44613. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44614. if (this.environmentTexture) {
  44615. activeTextures.push(this.environmentTexture);
  44616. }
  44617. if (this.normalTexture) {
  44618. activeTextures.push(this.normalTexture);
  44619. }
  44620. if (this.emissiveTexture) {
  44621. activeTextures.push(this.emissiveTexture);
  44622. }
  44623. if (this.occlusionTexture) {
  44624. activeTextures.push(this.occlusionTexture);
  44625. }
  44626. if (this.lightmapTexture) {
  44627. activeTextures.push(this.lightmapTexture);
  44628. }
  44629. return activeTextures;
  44630. };
  44631. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44632. if (_super.prototype.hasTexture.call(this, texture)) {
  44633. return true;
  44634. }
  44635. if (this.lightmapTexture === texture) {
  44636. return true;
  44637. }
  44638. return false;
  44639. };
  44640. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44641. return "PBRBaseSimpleMaterial";
  44642. };
  44643. __decorate([
  44644. BABYLON.serialize(),
  44645. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44646. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44647. __decorate([
  44648. BABYLON.serialize(),
  44649. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44650. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44651. __decorate([
  44652. BABYLON.serializeAsTexture(),
  44653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44654. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44655. __decorate([
  44656. BABYLON.serialize(),
  44657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44658. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44659. __decorate([
  44660. BABYLON.serialize(),
  44661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44662. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44663. __decorate([
  44664. BABYLON.serializeAsTexture(),
  44665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44666. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44667. __decorate([
  44668. BABYLON.serializeAsColor3("emissive"),
  44669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44670. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44671. __decorate([
  44672. BABYLON.serializeAsTexture(),
  44673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44674. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44675. __decorate([
  44676. BABYLON.serialize(),
  44677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44678. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44679. __decorate([
  44680. BABYLON.serializeAsTexture(),
  44681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44682. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44683. __decorate([
  44684. BABYLON.serialize(),
  44685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44686. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44687. __decorate([
  44688. BABYLON.serialize()
  44689. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44690. __decorate([
  44691. BABYLON.serializeAsTexture(),
  44692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44693. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44694. __decorate([
  44695. BABYLON.serialize(),
  44696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44697. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44698. return PBRBaseSimpleMaterial;
  44699. }(BABYLON.PBRBaseMaterial));
  44700. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44701. })(BABYLON || (BABYLON = {}));
  44702. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44703. var BABYLON;
  44704. (function (BABYLON) {
  44705. /**
  44706. * The Physically based material of BJS.
  44707. *
  44708. * This offers the main features of a standard PBR material.
  44709. * For more information, please refer to the documentation :
  44710. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44711. */
  44712. var PBRMaterial = /** @class */ (function (_super) {
  44713. __extends(PBRMaterial, _super);
  44714. /**
  44715. * Instantiates a new PBRMaterial instance.
  44716. *
  44717. * @param name The material name
  44718. * @param scene The scene the material will be use in.
  44719. */
  44720. function PBRMaterial(name, scene) {
  44721. var _this = _super.call(this, name, scene) || this;
  44722. /**
  44723. * Intensity of the direct lights e.g. the four lights available in your scene.
  44724. * This impacts both the direct diffuse and specular highlights.
  44725. */
  44726. _this.directIntensity = 1.0;
  44727. /**
  44728. * Intensity of the emissive part of the material.
  44729. * This helps controlling the emissive effect without modifying the emissive color.
  44730. */
  44731. _this.emissiveIntensity = 1.0;
  44732. /**
  44733. * Intensity of the environment e.g. how much the environment will light the object
  44734. * either through harmonics for rough material or through the refelction for shiny ones.
  44735. */
  44736. _this.environmentIntensity = 1.0;
  44737. /**
  44738. * This is a special control allowing the reduction of the specular highlights coming from the
  44739. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44740. */
  44741. _this.specularIntensity = 1.0;
  44742. /**
  44743. * Debug Control allowing disabling the bump map on this material.
  44744. */
  44745. _this.disableBumpMap = false;
  44746. /**
  44747. * AKA Occlusion Texture Intensity in other nomenclature.
  44748. */
  44749. _this.ambientTextureStrength = 1.0;
  44750. /**
  44751. * The color of a material in ambient lighting.
  44752. */
  44753. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44754. /**
  44755. * AKA Diffuse Color in other nomenclature.
  44756. */
  44757. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44758. /**
  44759. * AKA Specular Color in other nomenclature.
  44760. */
  44761. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44762. /**
  44763. * The color reflected from the material.
  44764. */
  44765. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44766. /**
  44767. * The color emitted from the material.
  44768. */
  44769. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44770. /**
  44771. * AKA Glossiness in other nomenclature.
  44772. */
  44773. _this.microSurface = 1.0;
  44774. /**
  44775. * source material index of refraction (IOR)' / 'destination material IOR.
  44776. */
  44777. _this.indexOfRefraction = 0.66;
  44778. /**
  44779. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44780. */
  44781. _this.invertRefractionY = false;
  44782. /**
  44783. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44784. * Materials half opaque for instance using refraction could benefit from this control.
  44785. */
  44786. _this.linkRefractionWithTransparency = false;
  44787. _this.useLightmapAsShadowmap = false;
  44788. /**
  44789. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44790. */
  44791. _this.useAlphaFromAlbedoTexture = false;
  44792. /**
  44793. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44794. */
  44795. _this.forceAlphaTest = false;
  44796. /**
  44797. * Defines the alpha limits in alpha test mode.
  44798. */
  44799. _this.alphaCutOff = 0.4;
  44800. /**
  44801. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44802. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44803. */
  44804. _this.useSpecularOverAlpha = true;
  44805. /**
  44806. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44807. */
  44808. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44809. /**
  44810. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44811. */
  44812. _this.useRoughnessFromMetallicTextureAlpha = true;
  44813. /**
  44814. * Specifies if the metallic texture contains the roughness information in its green channel.
  44815. */
  44816. _this.useRoughnessFromMetallicTextureGreen = false;
  44817. /**
  44818. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44819. */
  44820. _this.useMetallnessFromMetallicTextureBlue = false;
  44821. /**
  44822. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44823. */
  44824. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44825. /**
  44826. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44827. */
  44828. _this.useAmbientInGrayScale = false;
  44829. /**
  44830. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44831. * The material will try to infer what glossiness each pixel should be.
  44832. */
  44833. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44834. /**
  44835. * BJS is using an harcoded light falloff based on a manually sets up range.
  44836. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44837. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44838. */
  44839. _this.usePhysicalLightFalloff = true;
  44840. /**
  44841. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44842. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44843. */
  44844. _this.useRadianceOverAlpha = true;
  44845. /**
  44846. * Allows using an object space normal map (instead of tangent space).
  44847. */
  44848. _this.useObjectSpaceNormalMap = false;
  44849. /**
  44850. * Allows using the bump map in parallax mode.
  44851. */
  44852. _this.useParallax = false;
  44853. /**
  44854. * Allows using the bump map in parallax occlusion mode.
  44855. */
  44856. _this.useParallaxOcclusion = false;
  44857. /**
  44858. * Controls the scale bias of the parallax mode.
  44859. */
  44860. _this.parallaxScaleBias = 0.05;
  44861. /**
  44862. * If sets to true, disables all the lights affecting the material.
  44863. */
  44864. _this.disableLighting = false;
  44865. /**
  44866. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44867. */
  44868. _this.forceIrradianceInFragment = false;
  44869. /**
  44870. * Number of Simultaneous lights allowed on the material.
  44871. */
  44872. _this.maxSimultaneousLights = 4;
  44873. /**
  44874. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44875. */
  44876. _this.invertNormalMapX = false;
  44877. /**
  44878. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44879. */
  44880. _this.invertNormalMapY = false;
  44881. /**
  44882. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44883. */
  44884. _this.twoSidedLighting = false;
  44885. /**
  44886. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44887. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44888. */
  44889. _this.useAlphaFresnel = false;
  44890. /**
  44891. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44892. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44893. */
  44894. _this.useLinearAlphaFresnel = false;
  44895. /**
  44896. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44897. * And/Or occlude the blended part.
  44898. */
  44899. _this.environmentBRDFTexture = null;
  44900. /**
  44901. * Force normal to face away from face.
  44902. */
  44903. _this.forceNormalForward = false;
  44904. /**
  44905. * Enables specular anti aliasing in the PBR shader.
  44906. * It will both interacts on the Geometry for analytical and IBL lighting.
  44907. * It also prefilter the roughness map based on the bump values.
  44908. */
  44909. _this.enableSpecularAntiAliasing = false;
  44910. /**
  44911. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44912. * makes the reflect vector face the model (under horizon).
  44913. */
  44914. _this.useHorizonOcclusion = true;
  44915. /**
  44916. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44917. * too much the area relying on ambient texture to define their ambient occlusion.
  44918. */
  44919. _this.useRadianceOcclusion = true;
  44920. /**
  44921. * If set to true, no lighting calculations will be applied.
  44922. */
  44923. _this.unlit = false;
  44924. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44925. return _this;
  44926. }
  44927. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  44928. /**
  44929. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  44930. */
  44931. get: function () {
  44932. return this._PBRMATERIAL_OPAQUE;
  44933. },
  44934. enumerable: true,
  44935. configurable: true
  44936. });
  44937. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  44938. /**
  44939. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44940. */
  44941. get: function () {
  44942. return this._PBRMATERIAL_ALPHATEST;
  44943. },
  44944. enumerable: true,
  44945. configurable: true
  44946. });
  44947. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  44948. /**
  44949. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44950. */
  44951. get: function () {
  44952. return this._PBRMATERIAL_ALPHABLEND;
  44953. },
  44954. enumerable: true,
  44955. configurable: true
  44956. });
  44957. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  44958. /**
  44959. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44960. * They are also discarded below the alpha cutoff threshold to improve performances.
  44961. */
  44962. get: function () {
  44963. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  44964. },
  44965. enumerable: true,
  44966. configurable: true
  44967. });
  44968. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44969. /**
  44970. * Gets the image processing configuration used either in this material.
  44971. */
  44972. get: function () {
  44973. return this._imageProcessingConfiguration;
  44974. },
  44975. /**
  44976. * Sets the Default image processing configuration used either in the this material.
  44977. *
  44978. * If sets to null, the scene one is in use.
  44979. */
  44980. set: function (value) {
  44981. this._attachImageProcessingConfiguration(value);
  44982. // Ensure the effect will be rebuilt.
  44983. this._markAllSubMeshesAsTexturesDirty();
  44984. },
  44985. enumerable: true,
  44986. configurable: true
  44987. });
  44988. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  44989. /**
  44990. * Gets wether the color curves effect is enabled.
  44991. */
  44992. get: function () {
  44993. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44994. },
  44995. /**
  44996. * Sets wether the color curves effect is enabled.
  44997. */
  44998. set: function (value) {
  44999. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45000. },
  45001. enumerable: true,
  45002. configurable: true
  45003. });
  45004. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45005. /**
  45006. * Gets wether the color grading effect is enabled.
  45007. */
  45008. get: function () {
  45009. return this.imageProcessingConfiguration.colorGradingEnabled;
  45010. },
  45011. /**
  45012. * Gets wether the color grading effect is enabled.
  45013. */
  45014. set: function (value) {
  45015. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45016. },
  45017. enumerable: true,
  45018. configurable: true
  45019. });
  45020. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45021. /**
  45022. * Gets wether tonemapping is enabled or not.
  45023. */
  45024. get: function () {
  45025. return this._imageProcessingConfiguration.toneMappingEnabled;
  45026. },
  45027. /**
  45028. * Sets wether tonemapping is enabled or not
  45029. */
  45030. set: function (value) {
  45031. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45032. },
  45033. enumerable: true,
  45034. configurable: true
  45035. });
  45036. ;
  45037. ;
  45038. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45039. /**
  45040. * The camera exposure used on this material.
  45041. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45042. * This corresponds to a photographic exposure.
  45043. */
  45044. get: function () {
  45045. return this._imageProcessingConfiguration.exposure;
  45046. },
  45047. /**
  45048. * The camera exposure used on this material.
  45049. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45050. * This corresponds to a photographic exposure.
  45051. */
  45052. set: function (value) {
  45053. this._imageProcessingConfiguration.exposure = value;
  45054. },
  45055. enumerable: true,
  45056. configurable: true
  45057. });
  45058. ;
  45059. ;
  45060. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45061. /**
  45062. * Gets The camera contrast used on this material.
  45063. */
  45064. get: function () {
  45065. return this._imageProcessingConfiguration.contrast;
  45066. },
  45067. /**
  45068. * Sets The camera contrast used on this material.
  45069. */
  45070. set: function (value) {
  45071. this._imageProcessingConfiguration.contrast = value;
  45072. },
  45073. enumerable: true,
  45074. configurable: true
  45075. });
  45076. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45077. /**
  45078. * Gets the Color Grading 2D Lookup Texture.
  45079. */
  45080. get: function () {
  45081. return this._imageProcessingConfiguration.colorGradingTexture;
  45082. },
  45083. /**
  45084. * Sets the Color Grading 2D Lookup Texture.
  45085. */
  45086. set: function (value) {
  45087. this._imageProcessingConfiguration.colorGradingTexture = value;
  45088. },
  45089. enumerable: true,
  45090. configurable: true
  45091. });
  45092. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45093. /**
  45094. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45095. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45096. * 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;
  45097. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45098. */
  45099. get: function () {
  45100. return this._imageProcessingConfiguration.colorCurves;
  45101. },
  45102. /**
  45103. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45104. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45105. * 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;
  45106. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45107. */
  45108. set: function (value) {
  45109. this._imageProcessingConfiguration.colorCurves = value;
  45110. },
  45111. enumerable: true,
  45112. configurable: true
  45113. });
  45114. /**
  45115. * Returns the name of this material class.
  45116. */
  45117. PBRMaterial.prototype.getClassName = function () {
  45118. return "PBRMaterial";
  45119. };
  45120. /**
  45121. * Returns an array of the actively used textures.
  45122. * @returns - Array of BaseTextures
  45123. */
  45124. PBRMaterial.prototype.getActiveTextures = function () {
  45125. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45126. if (this._albedoTexture) {
  45127. activeTextures.push(this._albedoTexture);
  45128. }
  45129. if (this._ambientTexture) {
  45130. activeTextures.push(this._ambientTexture);
  45131. }
  45132. if (this._opacityTexture) {
  45133. activeTextures.push(this._opacityTexture);
  45134. }
  45135. if (this._reflectionTexture) {
  45136. activeTextures.push(this._reflectionTexture);
  45137. }
  45138. if (this._emissiveTexture) {
  45139. activeTextures.push(this._emissiveTexture);
  45140. }
  45141. if (this._reflectivityTexture) {
  45142. activeTextures.push(this._reflectivityTexture);
  45143. }
  45144. if (this._metallicTexture) {
  45145. activeTextures.push(this._metallicTexture);
  45146. }
  45147. if (this._microSurfaceTexture) {
  45148. activeTextures.push(this._microSurfaceTexture);
  45149. }
  45150. if (this._bumpTexture) {
  45151. activeTextures.push(this._bumpTexture);
  45152. }
  45153. if (this._lightmapTexture) {
  45154. activeTextures.push(this._lightmapTexture);
  45155. }
  45156. if (this._refractionTexture) {
  45157. activeTextures.push(this._refractionTexture);
  45158. }
  45159. return activeTextures;
  45160. };
  45161. /**
  45162. * Checks to see if a texture is used in the material.
  45163. * @param texture - Base texture to use.
  45164. * @returns - Boolean specifying if a texture is used in the material.
  45165. */
  45166. PBRMaterial.prototype.hasTexture = function (texture) {
  45167. if (_super.prototype.hasTexture.call(this, texture)) {
  45168. return true;
  45169. }
  45170. if (this._albedoTexture === texture) {
  45171. return true;
  45172. }
  45173. if (this._ambientTexture === texture) {
  45174. return true;
  45175. }
  45176. if (this._opacityTexture === texture) {
  45177. return true;
  45178. }
  45179. if (this._reflectionTexture === texture) {
  45180. return true;
  45181. }
  45182. if (this._reflectivityTexture === texture) {
  45183. return true;
  45184. }
  45185. if (this._metallicTexture === texture) {
  45186. return true;
  45187. }
  45188. if (this._microSurfaceTexture === texture) {
  45189. return true;
  45190. }
  45191. if (this._bumpTexture === texture) {
  45192. return true;
  45193. }
  45194. if (this._lightmapTexture === texture) {
  45195. return true;
  45196. }
  45197. if (this._refractionTexture === texture) {
  45198. return true;
  45199. }
  45200. return false;
  45201. };
  45202. /**
  45203. * Makes a duplicate of the current material.
  45204. * @param name - name to use for the new material.
  45205. */
  45206. PBRMaterial.prototype.clone = function (name) {
  45207. var _this = this;
  45208. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45209. clone.id = name;
  45210. clone.name = name;
  45211. return clone;
  45212. };
  45213. /**
  45214. * Serializes this PBR Material.
  45215. * @returns - An object with the serialized material.
  45216. */
  45217. PBRMaterial.prototype.serialize = function () {
  45218. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45219. serializationObject.customType = "BABYLON.PBRMaterial";
  45220. return serializationObject;
  45221. };
  45222. // Statics
  45223. /**
  45224. * Parses a PBR Material from a serialized object.
  45225. * @param source - Serialized object.
  45226. * @param scene - BJS scene instance.
  45227. * @param rootUrl - url for the scene object
  45228. * @returns - PBRMaterial
  45229. */
  45230. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45231. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45232. };
  45233. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45234. /**
  45235. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45236. */
  45237. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45238. /**
  45239. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45240. */
  45241. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45242. /**
  45243. * 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.
  45244. * They are also discarded below the alpha cutoff threshold to improve performances.
  45245. */
  45246. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45247. __decorate([
  45248. BABYLON.serialize(),
  45249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45250. ], PBRMaterial.prototype, "directIntensity", void 0);
  45251. __decorate([
  45252. BABYLON.serialize(),
  45253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45254. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45255. __decorate([
  45256. BABYLON.serialize(),
  45257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45258. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45259. __decorate([
  45260. BABYLON.serialize(),
  45261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45262. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45263. __decorate([
  45264. BABYLON.serialize(),
  45265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45266. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45267. __decorate([
  45268. BABYLON.serializeAsTexture(),
  45269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45270. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45271. __decorate([
  45272. BABYLON.serializeAsTexture(),
  45273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45274. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45275. __decorate([
  45276. BABYLON.serialize(),
  45277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45278. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45279. __decorate([
  45280. BABYLON.serializeAsTexture(),
  45281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45282. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45283. __decorate([
  45284. BABYLON.serializeAsTexture(),
  45285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45286. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45287. __decorate([
  45288. BABYLON.serializeAsTexture(),
  45289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45290. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45291. __decorate([
  45292. BABYLON.serializeAsTexture(),
  45293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45294. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45295. __decorate([
  45296. BABYLON.serializeAsTexture(),
  45297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45298. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45299. __decorate([
  45300. BABYLON.serialize(),
  45301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45302. ], PBRMaterial.prototype, "metallic", void 0);
  45303. __decorate([
  45304. BABYLON.serialize(),
  45305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45306. ], PBRMaterial.prototype, "roughness", void 0);
  45307. __decorate([
  45308. BABYLON.serializeAsTexture(),
  45309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45310. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45311. __decorate([
  45312. BABYLON.serializeAsTexture(),
  45313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45314. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45315. __decorate([
  45316. BABYLON.serializeAsTexture(),
  45317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45318. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45319. __decorate([
  45320. BABYLON.serializeAsTexture(),
  45321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45322. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45323. __decorate([
  45324. BABYLON.serializeAsColor3("ambient"),
  45325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45326. ], PBRMaterial.prototype, "ambientColor", void 0);
  45327. __decorate([
  45328. BABYLON.serializeAsColor3("albedo"),
  45329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45330. ], PBRMaterial.prototype, "albedoColor", void 0);
  45331. __decorate([
  45332. BABYLON.serializeAsColor3("reflectivity"),
  45333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45334. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45335. __decorate([
  45336. BABYLON.serializeAsColor3("reflection"),
  45337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45338. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45339. __decorate([
  45340. BABYLON.serializeAsColor3("emissive"),
  45341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45342. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45343. __decorate([
  45344. BABYLON.serialize(),
  45345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45346. ], PBRMaterial.prototype, "microSurface", void 0);
  45347. __decorate([
  45348. BABYLON.serialize(),
  45349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45350. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45351. __decorate([
  45352. BABYLON.serialize(),
  45353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45354. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45355. __decorate([
  45356. BABYLON.serialize(),
  45357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45358. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45359. __decorate([
  45360. BABYLON.serialize(),
  45361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45362. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45363. __decorate([
  45364. BABYLON.serialize(),
  45365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45366. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45367. __decorate([
  45368. BABYLON.serialize(),
  45369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45370. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45371. __decorate([
  45372. BABYLON.serialize(),
  45373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45374. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45375. __decorate([
  45376. BABYLON.serialize(),
  45377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45378. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45379. __decorate([
  45380. BABYLON.serialize(),
  45381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45382. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45383. __decorate([
  45384. BABYLON.serialize(),
  45385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45386. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45387. __decorate([
  45388. BABYLON.serialize(),
  45389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45390. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45391. __decorate([
  45392. BABYLON.serialize(),
  45393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45394. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45395. __decorate([
  45396. BABYLON.serialize(),
  45397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45398. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45399. __decorate([
  45400. BABYLON.serialize(),
  45401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45402. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45403. __decorate([
  45404. BABYLON.serialize(),
  45405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45406. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45407. __decorate([
  45408. BABYLON.serialize(),
  45409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45410. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45411. __decorate([
  45412. BABYLON.serialize(),
  45413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45414. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45415. __decorate([
  45416. BABYLON.serialize(),
  45417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45418. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45419. __decorate([
  45420. BABYLON.serialize(),
  45421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45422. ], PBRMaterial.prototype, "useParallax", void 0);
  45423. __decorate([
  45424. BABYLON.serialize(),
  45425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45426. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45427. __decorate([
  45428. BABYLON.serialize(),
  45429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45430. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45431. __decorate([
  45432. BABYLON.serialize(),
  45433. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45434. ], PBRMaterial.prototype, "disableLighting", void 0);
  45435. __decorate([
  45436. BABYLON.serialize(),
  45437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45438. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45439. __decorate([
  45440. BABYLON.serialize(),
  45441. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45442. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45443. __decorate([
  45444. BABYLON.serialize(),
  45445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45446. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45447. __decorate([
  45448. BABYLON.serialize(),
  45449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45450. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45451. __decorate([
  45452. BABYLON.serialize(),
  45453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45454. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45455. __decorate([
  45456. BABYLON.serialize(),
  45457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45458. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45459. __decorate([
  45460. BABYLON.serialize(),
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45462. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45463. __decorate([
  45464. BABYLON.serializeAsTexture(),
  45465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45466. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45467. __decorate([
  45468. BABYLON.serialize(),
  45469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45470. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45471. __decorate([
  45472. BABYLON.serialize(),
  45473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45474. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45475. __decorate([
  45476. BABYLON.serialize(),
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45478. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45479. __decorate([
  45480. BABYLON.serialize(),
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45483. __decorate([
  45484. BABYLON.serialize(),
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45486. ], PBRMaterial.prototype, "unlit", void 0);
  45487. return PBRMaterial;
  45488. }(BABYLON.PBRBaseMaterial));
  45489. BABYLON.PBRMaterial = PBRMaterial;
  45490. })(BABYLON || (BABYLON = {}));
  45491. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45492. var BABYLON;
  45493. (function (BABYLON) {
  45494. /**
  45495. * The PBR material of BJS following the metal roughness convention.
  45496. *
  45497. * This fits to the PBR convention in the GLTF definition:
  45498. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45499. */
  45500. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45501. __extends(PBRMetallicRoughnessMaterial, _super);
  45502. /**
  45503. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45504. *
  45505. * @param name The material name
  45506. * @param scene The scene the material will be use in.
  45507. */
  45508. function PBRMetallicRoughnessMaterial(name, scene) {
  45509. var _this = _super.call(this, name, scene) || this;
  45510. _this._useRoughnessFromMetallicTextureAlpha = false;
  45511. _this._useRoughnessFromMetallicTextureGreen = true;
  45512. _this._useMetallnessFromMetallicTextureBlue = true;
  45513. _this.metallic = 1.0;
  45514. _this.roughness = 1.0;
  45515. return _this;
  45516. }
  45517. /**
  45518. * Return the currrent class name of the material.
  45519. */
  45520. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45521. return "PBRMetallicRoughnessMaterial";
  45522. };
  45523. /**
  45524. * Return the active textures of the material.
  45525. */
  45526. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45527. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45528. if (this.baseTexture) {
  45529. activeTextures.push(this.baseTexture);
  45530. }
  45531. if (this.metallicRoughnessTexture) {
  45532. activeTextures.push(this.metallicRoughnessTexture);
  45533. }
  45534. return activeTextures;
  45535. };
  45536. /**
  45537. * Checks to see if a texture is used in the material.
  45538. * @param texture - Base texture to use.
  45539. * @returns - Boolean specifying if a texture is used in the material.
  45540. */
  45541. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45542. if (_super.prototype.hasTexture.call(this, texture)) {
  45543. return true;
  45544. }
  45545. if (this.baseTexture === texture) {
  45546. return true;
  45547. }
  45548. if (this.metallicRoughnessTexture === texture) {
  45549. return true;
  45550. }
  45551. return false;
  45552. };
  45553. /**
  45554. * Makes a duplicate of the current material.
  45555. * @param name - name to use for the new material.
  45556. */
  45557. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45558. var _this = this;
  45559. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45560. clone.id = name;
  45561. clone.name = name;
  45562. return clone;
  45563. };
  45564. /**
  45565. * Serialize the material to a parsable JSON object.
  45566. */
  45567. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45568. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45569. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45570. return serializationObject;
  45571. };
  45572. /**
  45573. * Parses a JSON object correponding to the serialize function.
  45574. */
  45575. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45576. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45577. };
  45578. __decorate([
  45579. BABYLON.serializeAsColor3(),
  45580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45581. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45582. __decorate([
  45583. BABYLON.serializeAsTexture(),
  45584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45585. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45586. __decorate([
  45587. BABYLON.serialize(),
  45588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45589. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45590. __decorate([
  45591. BABYLON.serialize(),
  45592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45593. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45594. __decorate([
  45595. BABYLON.serializeAsTexture(),
  45596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45597. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45598. return PBRMetallicRoughnessMaterial;
  45599. }(BABYLON.PBRBaseSimpleMaterial));
  45600. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45601. })(BABYLON || (BABYLON = {}));
  45602. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45603. var BABYLON;
  45604. (function (BABYLON) {
  45605. /**
  45606. * The PBR material of BJS following the specular glossiness convention.
  45607. *
  45608. * This fits to the PBR convention in the GLTF definition:
  45609. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45610. */
  45611. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45612. __extends(PBRSpecularGlossinessMaterial, _super);
  45613. /**
  45614. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45615. *
  45616. * @param name The material name
  45617. * @param scene The scene the material will be use in.
  45618. */
  45619. function PBRSpecularGlossinessMaterial(name, scene) {
  45620. var _this = _super.call(this, name, scene) || this;
  45621. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45622. return _this;
  45623. }
  45624. /**
  45625. * Return the currrent class name of the material.
  45626. */
  45627. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45628. return "PBRSpecularGlossinessMaterial";
  45629. };
  45630. /**
  45631. * Return the active textures of the material.
  45632. */
  45633. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45634. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45635. if (this.diffuseTexture) {
  45636. activeTextures.push(this.diffuseTexture);
  45637. }
  45638. if (this.specularGlossinessTexture) {
  45639. activeTextures.push(this.specularGlossinessTexture);
  45640. }
  45641. return activeTextures;
  45642. };
  45643. /**
  45644. * Checks to see if a texture is used in the material.
  45645. * @param texture - Base texture to use.
  45646. * @returns - Boolean specifying if a texture is used in the material.
  45647. */
  45648. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45649. if (_super.prototype.hasTexture.call(this, texture)) {
  45650. return true;
  45651. }
  45652. if (this.diffuseTexture === texture) {
  45653. return true;
  45654. }
  45655. if (this.specularGlossinessTexture === texture) {
  45656. return true;
  45657. }
  45658. return false;
  45659. };
  45660. /**
  45661. * Makes a duplicate of the current material.
  45662. * @param name - name to use for the new material.
  45663. */
  45664. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45665. var _this = this;
  45666. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45667. clone.id = name;
  45668. clone.name = name;
  45669. return clone;
  45670. };
  45671. /**
  45672. * Serialize the material to a parsable JSON object.
  45673. */
  45674. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45675. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45676. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45677. return serializationObject;
  45678. };
  45679. /**
  45680. * Parses a JSON object correponding to the serialize function.
  45681. */
  45682. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45683. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45684. };
  45685. __decorate([
  45686. BABYLON.serializeAsColor3("diffuse"),
  45687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45688. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45689. __decorate([
  45690. BABYLON.serializeAsTexture(),
  45691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45692. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45693. __decorate([
  45694. BABYLON.serializeAsColor3("specular"),
  45695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45696. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45697. __decorate([
  45698. BABYLON.serialize(),
  45699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45700. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45701. __decorate([
  45702. BABYLON.serializeAsTexture(),
  45703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45704. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45705. return PBRSpecularGlossinessMaterial;
  45706. }(BABYLON.PBRBaseSimpleMaterial));
  45707. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45708. })(BABYLON || (BABYLON = {}));
  45709. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45710. var BABYLON;
  45711. (function (BABYLON) {
  45712. BABYLON.CameraInputTypes = {};
  45713. var CameraInputsManager = /** @class */ (function () {
  45714. function CameraInputsManager(camera) {
  45715. this.attached = {};
  45716. this.camera = camera;
  45717. this.checkInputs = function () { };
  45718. }
  45719. /**
  45720. * Add an input method to a camera
  45721. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45722. * @param input camera input method
  45723. */
  45724. CameraInputsManager.prototype.add = function (input) {
  45725. var type = input.getSimpleName();
  45726. if (this.attached[type]) {
  45727. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45728. return;
  45729. }
  45730. this.attached[type] = input;
  45731. input.camera = this.camera;
  45732. //for checkInputs, we are dynamically creating a function
  45733. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45734. if (input.checkInputs) {
  45735. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45736. }
  45737. if (this.attachedElement) {
  45738. input.attachControl(this.attachedElement);
  45739. }
  45740. };
  45741. /**
  45742. * Remove a specific input method from a camera
  45743. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45744. * @param inputToRemove camera input method
  45745. */
  45746. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45747. for (var cam in this.attached) {
  45748. var input = this.attached[cam];
  45749. if (input === inputToRemove) {
  45750. input.detachControl(this.attachedElement);
  45751. input.camera = null;
  45752. delete this.attached[cam];
  45753. this.rebuildInputCheck();
  45754. }
  45755. }
  45756. };
  45757. CameraInputsManager.prototype.removeByType = function (inputType) {
  45758. for (var cam in this.attached) {
  45759. var input = this.attached[cam];
  45760. if (input.getClassName() === inputType) {
  45761. input.detachControl(this.attachedElement);
  45762. input.camera = null;
  45763. delete this.attached[cam];
  45764. this.rebuildInputCheck();
  45765. }
  45766. }
  45767. };
  45768. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45769. var current = this.checkInputs;
  45770. return function () {
  45771. current();
  45772. fn();
  45773. };
  45774. };
  45775. CameraInputsManager.prototype.attachInput = function (input) {
  45776. if (this.attachedElement) {
  45777. input.attachControl(this.attachedElement, this.noPreventDefault);
  45778. }
  45779. };
  45780. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45781. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45782. if (this.attachedElement) {
  45783. return;
  45784. }
  45785. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45786. this.attachedElement = element;
  45787. this.noPreventDefault = noPreventDefault;
  45788. for (var cam in this.attached) {
  45789. this.attached[cam].attachControl(element, noPreventDefault);
  45790. }
  45791. };
  45792. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45793. if (disconnect === void 0) { disconnect = false; }
  45794. if (this.attachedElement !== element) {
  45795. return;
  45796. }
  45797. for (var cam in this.attached) {
  45798. this.attached[cam].detachControl(element);
  45799. if (disconnect) {
  45800. this.attached[cam].camera = null;
  45801. }
  45802. }
  45803. this.attachedElement = null;
  45804. };
  45805. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45806. this.checkInputs = function () { };
  45807. for (var cam in this.attached) {
  45808. var input = this.attached[cam];
  45809. if (input.checkInputs) {
  45810. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45811. }
  45812. }
  45813. };
  45814. /**
  45815. * Remove all attached input methods from a camera
  45816. */
  45817. CameraInputsManager.prototype.clear = function () {
  45818. if (this.attachedElement) {
  45819. this.detachElement(this.attachedElement, true);
  45820. }
  45821. this.attached = {};
  45822. this.attachedElement = null;
  45823. this.checkInputs = function () { };
  45824. };
  45825. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45826. var inputs = {};
  45827. for (var cam in this.attached) {
  45828. var input = this.attached[cam];
  45829. var res = BABYLON.SerializationHelper.Serialize(input);
  45830. inputs[input.getClassName()] = res;
  45831. }
  45832. serializedCamera.inputsmgr = inputs;
  45833. };
  45834. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45835. var parsedInputs = parsedCamera.inputsmgr;
  45836. if (parsedInputs) {
  45837. this.clear();
  45838. for (var n in parsedInputs) {
  45839. var construct = BABYLON.CameraInputTypes[n];
  45840. if (construct) {
  45841. var parsedinput = parsedInputs[n];
  45842. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45843. this.add(input);
  45844. }
  45845. }
  45846. }
  45847. else {
  45848. //2016-03-08 this part is for managing backward compatibility
  45849. for (var n in this.attached) {
  45850. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45851. if (construct) {
  45852. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45853. this.remove(this.attached[n]);
  45854. this.add(input);
  45855. }
  45856. }
  45857. }
  45858. };
  45859. return CameraInputsManager;
  45860. }());
  45861. BABYLON.CameraInputsManager = CameraInputsManager;
  45862. })(BABYLON || (BABYLON = {}));
  45863. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45864. var BABYLON;
  45865. (function (BABYLON) {
  45866. var TargetCamera = /** @class */ (function (_super) {
  45867. __extends(TargetCamera, _super);
  45868. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45869. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45870. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45871. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45872. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45873. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45874. _this.speed = 2.0;
  45875. _this.noRotationConstraint = false;
  45876. _this.lockedTarget = null;
  45877. _this._currentTarget = BABYLON.Vector3.Zero();
  45878. _this._viewMatrix = BABYLON.Matrix.Zero();
  45879. _this._camMatrix = BABYLON.Matrix.Zero();
  45880. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45881. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45882. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45883. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45884. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45885. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45886. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45887. return _this;
  45888. }
  45889. TargetCamera.prototype.getFrontPosition = function (distance) {
  45890. this.getWorldMatrix();
  45891. var direction = this.getTarget().subtract(this.position);
  45892. direction.normalize();
  45893. direction.scaleInPlace(distance);
  45894. return this.globalPosition.add(direction);
  45895. };
  45896. TargetCamera.prototype._getLockedTargetPosition = function () {
  45897. if (!this.lockedTarget) {
  45898. return null;
  45899. }
  45900. if (this.lockedTarget.absolutePosition) {
  45901. this.lockedTarget.computeWorldMatrix();
  45902. }
  45903. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45904. };
  45905. TargetCamera.prototype.storeState = function () {
  45906. this._storedPosition = this.position.clone();
  45907. this._storedRotation = this.rotation.clone();
  45908. if (this.rotationQuaternion) {
  45909. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45910. }
  45911. return _super.prototype.storeState.call(this);
  45912. };
  45913. /**
  45914. * Restored camera state. You must call storeState() first
  45915. */
  45916. TargetCamera.prototype._restoreStateValues = function () {
  45917. if (!_super.prototype._restoreStateValues.call(this)) {
  45918. return false;
  45919. }
  45920. this.position = this._storedPosition.clone();
  45921. this.rotation = this._storedRotation.clone();
  45922. if (this.rotationQuaternion) {
  45923. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45924. }
  45925. this.cameraDirection.copyFromFloats(0, 0, 0);
  45926. this.cameraRotation.copyFromFloats(0, 0);
  45927. return true;
  45928. };
  45929. // Cache
  45930. TargetCamera.prototype._initCache = function () {
  45931. _super.prototype._initCache.call(this);
  45932. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45933. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45934. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45935. };
  45936. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45937. if (!ignoreParentClass) {
  45938. _super.prototype._updateCache.call(this);
  45939. }
  45940. var lockedTargetPosition = this._getLockedTargetPosition();
  45941. if (!lockedTargetPosition) {
  45942. this._cache.lockedTarget = null;
  45943. }
  45944. else {
  45945. if (!this._cache.lockedTarget) {
  45946. this._cache.lockedTarget = lockedTargetPosition.clone();
  45947. }
  45948. else {
  45949. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45950. }
  45951. }
  45952. this._cache.rotation.copyFrom(this.rotation);
  45953. if (this.rotationQuaternion)
  45954. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45955. };
  45956. // Synchronized
  45957. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45958. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45959. return false;
  45960. }
  45961. var lockedTargetPosition = this._getLockedTargetPosition();
  45962. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45963. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45964. };
  45965. // Methods
  45966. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  45967. var engine = this.getEngine();
  45968. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  45969. };
  45970. // Target
  45971. TargetCamera.prototype.setTarget = function (target) {
  45972. this.upVector.normalize();
  45973. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  45974. this._camMatrix.invert();
  45975. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  45976. var vDir = target.subtract(this.position);
  45977. if (vDir.x >= 0.0) {
  45978. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  45979. }
  45980. else {
  45981. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  45982. }
  45983. this.rotation.z = 0;
  45984. if (isNaN(this.rotation.x)) {
  45985. this.rotation.x = 0;
  45986. }
  45987. if (isNaN(this.rotation.y)) {
  45988. this.rotation.y = 0;
  45989. }
  45990. if (isNaN(this.rotation.z)) {
  45991. this.rotation.z = 0;
  45992. }
  45993. if (this.rotationQuaternion) {
  45994. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45995. }
  45996. };
  45997. /**
  45998. * Return the current target position of the camera. This value is expressed in local space.
  45999. */
  46000. TargetCamera.prototype.getTarget = function () {
  46001. return this._currentTarget;
  46002. };
  46003. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46004. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46005. };
  46006. TargetCamera.prototype._updatePosition = function () {
  46007. if (this.parent) {
  46008. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46009. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46010. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46011. return;
  46012. }
  46013. this.position.addInPlace(this.cameraDirection);
  46014. };
  46015. TargetCamera.prototype._checkInputs = function () {
  46016. var needToMove = this._decideIfNeedsToMove();
  46017. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46018. // Move
  46019. if (needToMove) {
  46020. this._updatePosition();
  46021. }
  46022. // Rotate
  46023. if (needToRotate) {
  46024. this.rotation.x += this.cameraRotation.x;
  46025. this.rotation.y += this.cameraRotation.y;
  46026. //rotate, if quaternion is set and rotation was used
  46027. if (this.rotationQuaternion) {
  46028. var len = this.rotation.lengthSquared();
  46029. if (len) {
  46030. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46031. }
  46032. }
  46033. if (!this.noRotationConstraint) {
  46034. var limit = (Math.PI / 2) * 0.95;
  46035. if (this.rotation.x > limit)
  46036. this.rotation.x = limit;
  46037. if (this.rotation.x < -limit)
  46038. this.rotation.x = -limit;
  46039. }
  46040. }
  46041. // Inertia
  46042. if (needToMove) {
  46043. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46044. this.cameraDirection.x = 0;
  46045. }
  46046. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46047. this.cameraDirection.y = 0;
  46048. }
  46049. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46050. this.cameraDirection.z = 0;
  46051. }
  46052. this.cameraDirection.scaleInPlace(this.inertia);
  46053. }
  46054. if (needToRotate) {
  46055. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46056. this.cameraRotation.x = 0;
  46057. }
  46058. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46059. this.cameraRotation.y = 0;
  46060. }
  46061. this.cameraRotation.scaleInPlace(this.inertia);
  46062. }
  46063. _super.prototype._checkInputs.call(this);
  46064. };
  46065. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46066. if (this.rotationQuaternion) {
  46067. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46068. }
  46069. else {
  46070. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46071. }
  46072. //update the up vector!
  46073. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46074. };
  46075. TargetCamera.prototype._getViewMatrix = function () {
  46076. if (this.lockedTarget) {
  46077. this.setTarget(this._getLockedTargetPosition());
  46078. }
  46079. // Compute
  46080. this._updateCameraRotationMatrix();
  46081. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46082. // Computing target and final matrix
  46083. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46084. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46085. return this._viewMatrix;
  46086. };
  46087. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46088. if (this.parent) {
  46089. var parentWorldMatrix = this.parent.getWorldMatrix();
  46090. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46091. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46092. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46093. this._markSyncedWithParent();
  46094. }
  46095. else {
  46096. this._globalPosition.copyFrom(this.position);
  46097. this._globalCurrentTarget.copyFrom(target);
  46098. this._globalCurrentUpVector.copyFrom(up);
  46099. }
  46100. if (this.getScene().useRightHandedSystem) {
  46101. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46102. }
  46103. else {
  46104. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46105. }
  46106. };
  46107. /**
  46108. * @override
  46109. * Override Camera.createRigCamera
  46110. */
  46111. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46112. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46113. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46114. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46115. if (!this.rotationQuaternion) {
  46116. this.rotationQuaternion = new BABYLON.Quaternion();
  46117. }
  46118. rigCamera._cameraRigParams = {};
  46119. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46120. }
  46121. return rigCamera;
  46122. }
  46123. return null;
  46124. };
  46125. /**
  46126. * @override
  46127. * Override Camera._updateRigCameras
  46128. */
  46129. TargetCamera.prototype._updateRigCameras = function () {
  46130. var camLeft = this._rigCameras[0];
  46131. var camRight = this._rigCameras[1];
  46132. switch (this.cameraRigMode) {
  46133. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46134. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46135. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46136. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46137. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46138. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46139. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46140. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46141. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46142. camLeft.setTarget(this.getTarget());
  46143. camRight.setTarget(this.getTarget());
  46144. break;
  46145. case BABYLON.Camera.RIG_MODE_VR:
  46146. if (camLeft.rotationQuaternion) {
  46147. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46148. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46149. }
  46150. else {
  46151. camLeft.rotation.copyFrom(this.rotation);
  46152. camRight.rotation.copyFrom(this.rotation);
  46153. }
  46154. camLeft.position.copyFrom(this.position);
  46155. camRight.position.copyFrom(this.position);
  46156. break;
  46157. }
  46158. _super.prototype._updateRigCameras.call(this);
  46159. };
  46160. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46161. if (!this._rigCamTransformMatrix) {
  46162. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46163. }
  46164. var target = this.getTarget();
  46165. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46166. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46167. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46168. };
  46169. TargetCamera.prototype.getClassName = function () {
  46170. return "TargetCamera";
  46171. };
  46172. __decorate([
  46173. BABYLON.serializeAsVector3()
  46174. ], TargetCamera.prototype, "rotation", void 0);
  46175. __decorate([
  46176. BABYLON.serialize()
  46177. ], TargetCamera.prototype, "speed", void 0);
  46178. __decorate([
  46179. BABYLON.serializeAsMeshReference("lockedTargetId")
  46180. ], TargetCamera.prototype, "lockedTarget", void 0);
  46181. return TargetCamera;
  46182. }(BABYLON.Camera));
  46183. BABYLON.TargetCamera = TargetCamera;
  46184. })(BABYLON || (BABYLON = {}));
  46185. //# sourceMappingURL=babylon.targetCamera.js.map
  46186. var BABYLON;
  46187. (function (BABYLON) {
  46188. var FreeCameraMouseInput = /** @class */ (function () {
  46189. function FreeCameraMouseInput(touchEnabled) {
  46190. if (touchEnabled === void 0) { touchEnabled = true; }
  46191. this.touchEnabled = touchEnabled;
  46192. this.buttons = [0, 1, 2];
  46193. this.angularSensibility = 2000.0;
  46194. this.previousPosition = null;
  46195. }
  46196. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46197. var _this = this;
  46198. var engine = this.camera.getEngine();
  46199. if (!this._pointerInput) {
  46200. this._pointerInput = function (p, s) {
  46201. var evt = p.event;
  46202. if (engine.isInVRExclusivePointerMode) {
  46203. return;
  46204. }
  46205. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46206. return;
  46207. }
  46208. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46209. return;
  46210. }
  46211. var srcElement = (evt.srcElement || evt.target);
  46212. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46213. try {
  46214. srcElement.setPointerCapture(evt.pointerId);
  46215. }
  46216. catch (e) {
  46217. //Nothing to do with the error. Execution will continue.
  46218. }
  46219. _this.previousPosition = {
  46220. x: evt.clientX,
  46221. y: evt.clientY
  46222. };
  46223. if (!noPreventDefault) {
  46224. evt.preventDefault();
  46225. element.focus();
  46226. }
  46227. }
  46228. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46229. try {
  46230. srcElement.releasePointerCapture(evt.pointerId);
  46231. }
  46232. catch (e) {
  46233. //Nothing to do with the error.
  46234. }
  46235. _this.previousPosition = null;
  46236. if (!noPreventDefault) {
  46237. evt.preventDefault();
  46238. }
  46239. }
  46240. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46241. if (!_this.previousPosition || engine.isPointerLock) {
  46242. return;
  46243. }
  46244. var offsetX = evt.clientX - _this.previousPosition.x;
  46245. if (_this.camera.getScene().useRightHandedSystem)
  46246. offsetX *= -1;
  46247. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46248. offsetX *= -1;
  46249. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46250. var offsetY = evt.clientY - _this.previousPosition.y;
  46251. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46252. _this.previousPosition = {
  46253. x: evt.clientX,
  46254. y: evt.clientY
  46255. };
  46256. if (!noPreventDefault) {
  46257. evt.preventDefault();
  46258. }
  46259. }
  46260. };
  46261. }
  46262. this._onMouseMove = function (evt) {
  46263. if (!engine.isPointerLock) {
  46264. return;
  46265. }
  46266. if (engine.isInVRExclusivePointerMode) {
  46267. return;
  46268. }
  46269. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46270. if (_this.camera.getScene().useRightHandedSystem)
  46271. offsetX *= -1;
  46272. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46273. offsetX *= -1;
  46274. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46275. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46276. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46277. _this.previousPosition = null;
  46278. if (!noPreventDefault) {
  46279. evt.preventDefault();
  46280. }
  46281. };
  46282. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46283. element.addEventListener("mousemove", this._onMouseMove, false);
  46284. };
  46285. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46286. if (this._observer && element) {
  46287. this.camera.getScene().onPointerObservable.remove(this._observer);
  46288. if (this._onMouseMove) {
  46289. element.removeEventListener("mousemove", this._onMouseMove);
  46290. }
  46291. this._observer = null;
  46292. this._onMouseMove = null;
  46293. this.previousPosition = null;
  46294. }
  46295. };
  46296. FreeCameraMouseInput.prototype.getClassName = function () {
  46297. return "FreeCameraMouseInput";
  46298. };
  46299. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46300. return "mouse";
  46301. };
  46302. __decorate([
  46303. BABYLON.serialize()
  46304. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46305. __decorate([
  46306. BABYLON.serialize()
  46307. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46308. return FreeCameraMouseInput;
  46309. }());
  46310. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46311. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46312. })(BABYLON || (BABYLON = {}));
  46313. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46314. var BABYLON;
  46315. (function (BABYLON) {
  46316. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46317. function FreeCameraKeyboardMoveInput() {
  46318. this._keys = new Array();
  46319. this.keysUp = [38];
  46320. this.keysDown = [40];
  46321. this.keysLeft = [37];
  46322. this.keysRight = [39];
  46323. }
  46324. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46325. var _this = this;
  46326. if (this._onCanvasBlurObserver) {
  46327. return;
  46328. }
  46329. this._scene = this.camera.getScene();
  46330. this._engine = this._scene.getEngine();
  46331. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46332. _this._keys = [];
  46333. });
  46334. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46335. var evt = info.event;
  46336. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46337. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46338. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46339. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46340. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46341. var index = _this._keys.indexOf(evt.keyCode);
  46342. if (index === -1) {
  46343. _this._keys.push(evt.keyCode);
  46344. }
  46345. if (!noPreventDefault) {
  46346. evt.preventDefault();
  46347. }
  46348. }
  46349. }
  46350. else {
  46351. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46352. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46353. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46354. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46355. var index = _this._keys.indexOf(evt.keyCode);
  46356. if (index >= 0) {
  46357. _this._keys.splice(index, 1);
  46358. }
  46359. if (!noPreventDefault) {
  46360. evt.preventDefault();
  46361. }
  46362. }
  46363. }
  46364. });
  46365. };
  46366. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46367. if (this._scene) {
  46368. if (this._onKeyboardObserver) {
  46369. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46370. }
  46371. if (this._onCanvasBlurObserver) {
  46372. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46373. }
  46374. this._onKeyboardObserver = null;
  46375. this._onCanvasBlurObserver = null;
  46376. }
  46377. this._keys = [];
  46378. };
  46379. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46380. if (this._onKeyboardObserver) {
  46381. var camera = this.camera;
  46382. // Keyboard
  46383. for (var index = 0; index < this._keys.length; index++) {
  46384. var keyCode = this._keys[index];
  46385. var speed = camera._computeLocalCameraSpeed();
  46386. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46387. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46388. }
  46389. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46390. camera._localDirection.copyFromFloats(0, 0, speed);
  46391. }
  46392. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46393. camera._localDirection.copyFromFloats(speed, 0, 0);
  46394. }
  46395. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46396. camera._localDirection.copyFromFloats(0, 0, -speed);
  46397. }
  46398. if (camera.getScene().useRightHandedSystem) {
  46399. camera._localDirection.z *= -1;
  46400. }
  46401. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46402. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46403. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46404. }
  46405. }
  46406. };
  46407. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46408. return "FreeCameraKeyboardMoveInput";
  46409. };
  46410. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46411. this._keys = [];
  46412. };
  46413. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46414. return "keyboard";
  46415. };
  46416. __decorate([
  46417. BABYLON.serialize()
  46418. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46419. __decorate([
  46420. BABYLON.serialize()
  46421. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46422. __decorate([
  46423. BABYLON.serialize()
  46424. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46425. __decorate([
  46426. BABYLON.serialize()
  46427. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46428. return FreeCameraKeyboardMoveInput;
  46429. }());
  46430. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46431. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46432. })(BABYLON || (BABYLON = {}));
  46433. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46434. var BABYLON;
  46435. (function (BABYLON) {
  46436. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46437. __extends(FreeCameraInputsManager, _super);
  46438. function FreeCameraInputsManager(camera) {
  46439. return _super.call(this, camera) || this;
  46440. }
  46441. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46442. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46443. return this;
  46444. };
  46445. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46446. if (touchEnabled === void 0) { touchEnabled = true; }
  46447. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46448. return this;
  46449. };
  46450. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46451. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46452. return this;
  46453. };
  46454. FreeCameraInputsManager.prototype.addTouch = function () {
  46455. this.add(new BABYLON.FreeCameraTouchInput());
  46456. return this;
  46457. };
  46458. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46459. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46460. return this;
  46461. };
  46462. return FreeCameraInputsManager;
  46463. }(BABYLON.CameraInputsManager));
  46464. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46465. })(BABYLON || (BABYLON = {}));
  46466. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46467. var BABYLON;
  46468. (function (BABYLON) {
  46469. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46470. // Forcing to use the Universal camera
  46471. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46472. });
  46473. var FreeCamera = /** @class */ (function (_super) {
  46474. __extends(FreeCamera, _super);
  46475. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46476. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46477. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46478. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46479. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46480. _this.checkCollisions = false;
  46481. _this.applyGravity = false;
  46482. _this._needMoveForGravity = false;
  46483. _this._oldPosition = BABYLON.Vector3.Zero();
  46484. _this._diffPosition = BABYLON.Vector3.Zero();
  46485. _this._newPosition = BABYLON.Vector3.Zero();
  46486. // Collisions
  46487. _this._collisionMask = -1;
  46488. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46489. if (collidedMesh === void 0) { collidedMesh = null; }
  46490. //TODO move this to the collision coordinator!
  46491. if (_this.getScene().workerCollisions)
  46492. newPosition.multiplyInPlace(_this._collider._radius);
  46493. var updatePosition = function (newPos) {
  46494. _this._newPosition.copyFrom(newPos);
  46495. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46496. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46497. _this.position.addInPlace(_this._diffPosition);
  46498. if (_this.onCollide && collidedMesh) {
  46499. _this.onCollide(collidedMesh);
  46500. }
  46501. }
  46502. };
  46503. updatePosition(newPosition);
  46504. };
  46505. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46506. _this.inputs.addKeyboard().addMouse();
  46507. return _this;
  46508. }
  46509. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46510. //-- begin properties for backward compatibility for inputs
  46511. /**
  46512. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46513. * Higher values reduce sensitivity.
  46514. */
  46515. get: function () {
  46516. var mouse = this.inputs.attached["mouse"];
  46517. if (mouse)
  46518. return mouse.angularSensibility;
  46519. return 0;
  46520. },
  46521. /**
  46522. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46523. * Higher values reduce sensitivity.
  46524. */
  46525. set: function (value) {
  46526. var mouse = this.inputs.attached["mouse"];
  46527. if (mouse)
  46528. mouse.angularSensibility = value;
  46529. },
  46530. enumerable: true,
  46531. configurable: true
  46532. });
  46533. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46534. get: function () {
  46535. var keyboard = this.inputs.attached["keyboard"];
  46536. if (keyboard)
  46537. return keyboard.keysUp;
  46538. return [];
  46539. },
  46540. set: function (value) {
  46541. var keyboard = this.inputs.attached["keyboard"];
  46542. if (keyboard)
  46543. keyboard.keysUp = value;
  46544. },
  46545. enumerable: true,
  46546. configurable: true
  46547. });
  46548. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46549. get: function () {
  46550. var keyboard = this.inputs.attached["keyboard"];
  46551. if (keyboard)
  46552. return keyboard.keysDown;
  46553. return [];
  46554. },
  46555. set: function (value) {
  46556. var keyboard = this.inputs.attached["keyboard"];
  46557. if (keyboard)
  46558. keyboard.keysDown = value;
  46559. },
  46560. enumerable: true,
  46561. configurable: true
  46562. });
  46563. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46564. get: function () {
  46565. var keyboard = this.inputs.attached["keyboard"];
  46566. if (keyboard)
  46567. return keyboard.keysLeft;
  46568. return [];
  46569. },
  46570. set: function (value) {
  46571. var keyboard = this.inputs.attached["keyboard"];
  46572. if (keyboard)
  46573. keyboard.keysLeft = value;
  46574. },
  46575. enumerable: true,
  46576. configurable: true
  46577. });
  46578. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46579. get: function () {
  46580. var keyboard = this.inputs.attached["keyboard"];
  46581. if (keyboard)
  46582. return keyboard.keysRight;
  46583. return [];
  46584. },
  46585. set: function (value) {
  46586. var keyboard = this.inputs.attached["keyboard"];
  46587. if (keyboard)
  46588. keyboard.keysRight = value;
  46589. },
  46590. enumerable: true,
  46591. configurable: true
  46592. });
  46593. // Controls
  46594. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46595. this.inputs.attachElement(element, noPreventDefault);
  46596. };
  46597. FreeCamera.prototype.detachControl = function (element) {
  46598. this.inputs.detachElement(element);
  46599. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46600. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46601. };
  46602. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46603. get: function () {
  46604. return this._collisionMask;
  46605. },
  46606. set: function (mask) {
  46607. this._collisionMask = !isNaN(mask) ? mask : -1;
  46608. },
  46609. enumerable: true,
  46610. configurable: true
  46611. });
  46612. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46613. var globalPosition;
  46614. if (this.parent) {
  46615. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46616. }
  46617. else {
  46618. globalPosition = this.position;
  46619. }
  46620. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46621. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46622. if (!this._collider) {
  46623. this._collider = new BABYLON.Collider();
  46624. }
  46625. this._collider._radius = this.ellipsoid;
  46626. this._collider.collisionMask = this._collisionMask;
  46627. //no need for clone, as long as gravity is not on.
  46628. var actualDisplacement = displacement;
  46629. //add gravity to the direction to prevent the dual-collision checking
  46630. if (this.applyGravity) {
  46631. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46632. actualDisplacement = displacement.add(this.getScene().gravity);
  46633. }
  46634. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46635. };
  46636. FreeCamera.prototype._checkInputs = function () {
  46637. if (!this._localDirection) {
  46638. this._localDirection = BABYLON.Vector3.Zero();
  46639. this._transformedDirection = BABYLON.Vector3.Zero();
  46640. }
  46641. this.inputs.checkInputs();
  46642. _super.prototype._checkInputs.call(this);
  46643. };
  46644. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46645. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46646. };
  46647. FreeCamera.prototype._updatePosition = function () {
  46648. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46649. this._collideWithWorld(this.cameraDirection);
  46650. }
  46651. else {
  46652. _super.prototype._updatePosition.call(this);
  46653. }
  46654. };
  46655. FreeCamera.prototype.dispose = function () {
  46656. this.inputs.clear();
  46657. _super.prototype.dispose.call(this);
  46658. };
  46659. FreeCamera.prototype.getClassName = function () {
  46660. return "FreeCamera";
  46661. };
  46662. __decorate([
  46663. BABYLON.serializeAsVector3()
  46664. ], FreeCamera.prototype, "ellipsoid", void 0);
  46665. __decorate([
  46666. BABYLON.serializeAsVector3()
  46667. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46668. __decorate([
  46669. BABYLON.serialize()
  46670. ], FreeCamera.prototype, "checkCollisions", void 0);
  46671. __decorate([
  46672. BABYLON.serialize()
  46673. ], FreeCamera.prototype, "applyGravity", void 0);
  46674. return FreeCamera;
  46675. }(BABYLON.TargetCamera));
  46676. BABYLON.FreeCamera = FreeCamera;
  46677. })(BABYLON || (BABYLON = {}));
  46678. //# sourceMappingURL=babylon.freeCamera.js.map
  46679. var BABYLON;
  46680. (function (BABYLON) {
  46681. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46682. function ArcRotateCameraKeyboardMoveInput() {
  46683. this._keys = new Array();
  46684. this.keysUp = [38];
  46685. this.keysDown = [40];
  46686. this.keysLeft = [37];
  46687. this.keysRight = [39];
  46688. this.keysReset = [220];
  46689. this.panningSensibility = 50.0;
  46690. this.zoomingSensibility = 25.0;
  46691. this.useAltToZoom = true;
  46692. }
  46693. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46694. var _this = this;
  46695. if (this._onCanvasBlurObserver) {
  46696. return;
  46697. }
  46698. this._scene = this.camera.getScene();
  46699. this._engine = this._scene.getEngine();
  46700. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46701. _this._keys = [];
  46702. });
  46703. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46704. var evt = info.event;
  46705. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46706. _this._ctrlPressed = evt.ctrlKey;
  46707. _this._altPressed = evt.altKey;
  46708. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46709. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46710. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46711. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46712. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46713. var index = _this._keys.indexOf(evt.keyCode);
  46714. if (index === -1) {
  46715. _this._keys.push(evt.keyCode);
  46716. }
  46717. if (evt.preventDefault) {
  46718. if (!noPreventDefault) {
  46719. evt.preventDefault();
  46720. }
  46721. }
  46722. }
  46723. }
  46724. else {
  46725. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46726. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46727. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46728. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46729. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46730. var index = _this._keys.indexOf(evt.keyCode);
  46731. if (index >= 0) {
  46732. _this._keys.splice(index, 1);
  46733. }
  46734. if (evt.preventDefault) {
  46735. if (!noPreventDefault) {
  46736. evt.preventDefault();
  46737. }
  46738. }
  46739. }
  46740. }
  46741. });
  46742. };
  46743. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46744. if (this._scene) {
  46745. if (this._onKeyboardObserver) {
  46746. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46747. }
  46748. if (this._onCanvasBlurObserver) {
  46749. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46750. }
  46751. this._onKeyboardObserver = null;
  46752. this._onCanvasBlurObserver = null;
  46753. }
  46754. this._keys = [];
  46755. };
  46756. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46757. if (this._onKeyboardObserver) {
  46758. var camera = this.camera;
  46759. for (var index = 0; index < this._keys.length; index++) {
  46760. var keyCode = this._keys[index];
  46761. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46762. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46763. camera.inertialPanningX -= 1 / this.panningSensibility;
  46764. }
  46765. else {
  46766. camera.inertialAlphaOffset -= 0.01;
  46767. }
  46768. }
  46769. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46770. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46771. camera.inertialPanningY += 1 / this.panningSensibility;
  46772. }
  46773. else if (this._altPressed && this.useAltToZoom) {
  46774. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46775. }
  46776. else {
  46777. camera.inertialBetaOffset -= 0.01;
  46778. }
  46779. }
  46780. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46781. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46782. camera.inertialPanningX += 1 / this.panningSensibility;
  46783. }
  46784. else {
  46785. camera.inertialAlphaOffset += 0.01;
  46786. }
  46787. }
  46788. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46789. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46790. camera.inertialPanningY -= 1 / this.panningSensibility;
  46791. }
  46792. else if (this._altPressed && this.useAltToZoom) {
  46793. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46794. }
  46795. else {
  46796. camera.inertialBetaOffset += 0.01;
  46797. }
  46798. }
  46799. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46800. camera.restoreState();
  46801. }
  46802. }
  46803. }
  46804. };
  46805. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46806. return "ArcRotateCameraKeyboardMoveInput";
  46807. };
  46808. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46809. return "keyboard";
  46810. };
  46811. __decorate([
  46812. BABYLON.serialize()
  46813. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46814. __decorate([
  46815. BABYLON.serialize()
  46816. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46817. __decorate([
  46818. BABYLON.serialize()
  46819. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46820. __decorate([
  46821. BABYLON.serialize()
  46822. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46823. __decorate([
  46824. BABYLON.serialize()
  46825. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46826. __decorate([
  46827. BABYLON.serialize()
  46828. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46829. __decorate([
  46830. BABYLON.serialize()
  46831. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46832. __decorate([
  46833. BABYLON.serialize()
  46834. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46835. return ArcRotateCameraKeyboardMoveInput;
  46836. }());
  46837. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46838. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46839. })(BABYLON || (BABYLON = {}));
  46840. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46841. var BABYLON;
  46842. (function (BABYLON) {
  46843. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46844. function ArcRotateCameraMouseWheelInput() {
  46845. this.wheelPrecision = 3.0;
  46846. /**
  46847. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46848. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46849. */
  46850. this.wheelDeltaPercentage = 0;
  46851. }
  46852. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46853. var _this = this;
  46854. this._wheel = function (p, s) {
  46855. //sanity check - this should be a PointerWheel event.
  46856. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46857. return;
  46858. var event = p.event;
  46859. var delta = 0;
  46860. if (event.wheelDelta) {
  46861. if (_this.wheelDeltaPercentage) {
  46862. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46863. if (event.wheelDelta > 0) {
  46864. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46865. }
  46866. else {
  46867. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46868. }
  46869. }
  46870. else {
  46871. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46872. }
  46873. }
  46874. else if (event.detail) {
  46875. delta = -event.detail / _this.wheelPrecision;
  46876. }
  46877. if (delta)
  46878. _this.camera.inertialRadiusOffset += delta;
  46879. if (event.preventDefault) {
  46880. if (!noPreventDefault) {
  46881. event.preventDefault();
  46882. }
  46883. }
  46884. };
  46885. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46886. };
  46887. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46888. if (this._observer && element) {
  46889. this.camera.getScene().onPointerObservable.remove(this._observer);
  46890. this._observer = null;
  46891. this._wheel = null;
  46892. }
  46893. };
  46894. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46895. return "ArcRotateCameraMouseWheelInput";
  46896. };
  46897. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46898. return "mousewheel";
  46899. };
  46900. __decorate([
  46901. BABYLON.serialize()
  46902. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46903. __decorate([
  46904. BABYLON.serialize()
  46905. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46906. return ArcRotateCameraMouseWheelInput;
  46907. }());
  46908. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46909. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46910. })(BABYLON || (BABYLON = {}));
  46911. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46912. var BABYLON;
  46913. (function (BABYLON) {
  46914. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46915. function ArcRotateCameraPointersInput() {
  46916. this.buttons = [0, 1, 2];
  46917. this.angularSensibilityX = 1000.0;
  46918. this.angularSensibilityY = 1000.0;
  46919. this.pinchPrecision = 12.0;
  46920. /**
  46921. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46922. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46923. */
  46924. this.pinchDeltaPercentage = 0;
  46925. this.panningSensibility = 1000.0;
  46926. this.multiTouchPanning = true;
  46927. this.multiTouchPanAndZoom = true;
  46928. this._isPanClick = false;
  46929. this.pinchInwards = true;
  46930. }
  46931. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46932. var _this = this;
  46933. var engine = this.camera.getEngine();
  46934. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46935. var pointA = null;
  46936. var pointB = null;
  46937. var previousPinchSquaredDistance = 0;
  46938. var initialDistance = 0;
  46939. var twoFingerActivityCount = 0;
  46940. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46941. this._pointerInput = function (p, s) {
  46942. var evt = p.event;
  46943. var isTouch = p.event.pointerType === "touch";
  46944. if (engine.isInVRExclusivePointerMode) {
  46945. return;
  46946. }
  46947. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46948. return;
  46949. }
  46950. var srcElement = (evt.srcElement || evt.target);
  46951. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46952. try {
  46953. srcElement.setPointerCapture(evt.pointerId);
  46954. }
  46955. catch (e) {
  46956. //Nothing to do with the error. Execution will continue.
  46957. }
  46958. // Manage panning with pan button click
  46959. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  46960. // manage pointers
  46961. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  46962. if (pointA === null) {
  46963. pointA = cacheSoloPointer;
  46964. }
  46965. else if (pointB === null) {
  46966. pointB = cacheSoloPointer;
  46967. }
  46968. if (!noPreventDefault) {
  46969. evt.preventDefault();
  46970. element.focus();
  46971. }
  46972. }
  46973. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  46974. _this.camera.restoreState();
  46975. }
  46976. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46977. try {
  46978. srcElement.releasePointerCapture(evt.pointerId);
  46979. }
  46980. catch (e) {
  46981. //Nothing to do with the error.
  46982. }
  46983. cacheSoloPointer = null;
  46984. previousPinchSquaredDistance = 0;
  46985. previousMultiTouchPanPosition.isPaning = false;
  46986. previousMultiTouchPanPosition.isPinching = false;
  46987. twoFingerActivityCount = 0;
  46988. initialDistance = 0;
  46989. if (!isTouch) {
  46990. pointB = null; // Mouse and pen are mono pointer
  46991. }
  46992. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  46993. //but emptying completly pointers collection is required to fix a bug on iPhone :
  46994. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  46995. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  46996. if (engine._badOS) {
  46997. pointA = pointB = null;
  46998. }
  46999. else {
  47000. //only remove the impacted pointer in case of multitouch allowing on most
  47001. //platforms switching from rotate to zoom and pan seamlessly.
  47002. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47003. pointA = pointB;
  47004. pointB = null;
  47005. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47006. }
  47007. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47008. pointB = null;
  47009. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47010. }
  47011. else {
  47012. pointA = pointB = null;
  47013. }
  47014. }
  47015. if (!noPreventDefault) {
  47016. evt.preventDefault();
  47017. }
  47018. }
  47019. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47020. if (!noPreventDefault) {
  47021. evt.preventDefault();
  47022. }
  47023. // One button down
  47024. if (pointA && pointB === null && cacheSoloPointer) {
  47025. if (_this.panningSensibility !== 0 &&
  47026. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47027. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47028. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47029. }
  47030. else {
  47031. var offsetX = evt.clientX - cacheSoloPointer.x;
  47032. var offsetY = evt.clientY - cacheSoloPointer.y;
  47033. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47034. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47035. }
  47036. cacheSoloPointer.x = evt.clientX;
  47037. cacheSoloPointer.y = evt.clientY;
  47038. }
  47039. // Two buttons down: pinch/pan
  47040. else if (pointA && pointB) {
  47041. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47042. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47043. ed.x = evt.clientX;
  47044. ed.y = evt.clientY;
  47045. var direction = _this.pinchInwards ? 1 : -1;
  47046. var distX = pointA.x - pointB.x;
  47047. var distY = pointA.y - pointB.y;
  47048. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47049. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47050. if (previousPinchSquaredDistance === 0) {
  47051. initialDistance = pinchDistance;
  47052. previousPinchSquaredDistance = pinchSquaredDistance;
  47053. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47054. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47055. return;
  47056. }
  47057. if (_this.multiTouchPanAndZoom) {
  47058. if (_this.pinchDeltaPercentage) {
  47059. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47060. }
  47061. else {
  47062. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47063. (_this.pinchPrecision *
  47064. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47065. direction);
  47066. }
  47067. if (_this.panningSensibility !== 0) {
  47068. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47069. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47070. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47071. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47072. previousMultiTouchPanPosition.x = pointersCenterX;
  47073. previousMultiTouchPanPosition.y = pointersCenterY;
  47074. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47075. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47076. }
  47077. }
  47078. else {
  47079. twoFingerActivityCount++;
  47080. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47081. if (_this.pinchDeltaPercentage) {
  47082. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47083. }
  47084. else {
  47085. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47086. (_this.pinchPrecision *
  47087. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47088. direction);
  47089. }
  47090. previousMultiTouchPanPosition.isPaning = false;
  47091. previousMultiTouchPanPosition.isPinching = true;
  47092. }
  47093. else {
  47094. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47095. if (!previousMultiTouchPanPosition.isPaning) {
  47096. previousMultiTouchPanPosition.isPaning = true;
  47097. previousMultiTouchPanPosition.isPinching = false;
  47098. previousMultiTouchPanPosition.x = ed.x;
  47099. previousMultiTouchPanPosition.y = ed.y;
  47100. return;
  47101. }
  47102. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47103. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47104. }
  47105. }
  47106. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47107. previousMultiTouchPanPosition.x = ed.x;
  47108. previousMultiTouchPanPosition.y = ed.y;
  47109. }
  47110. }
  47111. previousPinchSquaredDistance = pinchSquaredDistance;
  47112. }
  47113. }
  47114. };
  47115. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47116. this._onContextMenu = function (evt) {
  47117. evt.preventDefault();
  47118. };
  47119. if (!this.camera._useCtrlForPanning) {
  47120. element.addEventListener("contextmenu", this._onContextMenu, false);
  47121. }
  47122. this._onLostFocus = function () {
  47123. //this._keys = [];
  47124. pointA = pointB = null;
  47125. previousPinchSquaredDistance = 0;
  47126. previousMultiTouchPanPosition.isPaning = false;
  47127. previousMultiTouchPanPosition.isPinching = false;
  47128. twoFingerActivityCount = 0;
  47129. cacheSoloPointer = null;
  47130. initialDistance = 0;
  47131. };
  47132. this._onMouseMove = function (evt) {
  47133. if (!engine.isPointerLock) {
  47134. return;
  47135. }
  47136. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47137. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47138. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47139. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47140. if (!noPreventDefault) {
  47141. evt.preventDefault();
  47142. }
  47143. };
  47144. this._onGestureStart = function (e) {
  47145. if (window.MSGesture === undefined) {
  47146. return;
  47147. }
  47148. if (!_this._MSGestureHandler) {
  47149. _this._MSGestureHandler = new MSGesture();
  47150. _this._MSGestureHandler.target = element;
  47151. }
  47152. _this._MSGestureHandler.addPointer(e.pointerId);
  47153. };
  47154. this._onGesture = function (e) {
  47155. _this.camera.radius *= e.scale;
  47156. if (e.preventDefault) {
  47157. if (!noPreventDefault) {
  47158. e.stopPropagation();
  47159. e.preventDefault();
  47160. }
  47161. }
  47162. };
  47163. element.addEventListener("mousemove", this._onMouseMove, false);
  47164. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47165. element.addEventListener("MSGestureChange", this._onGesture, false);
  47166. BABYLON.Tools.RegisterTopRootEvents([
  47167. { name: "blur", handler: this._onLostFocus }
  47168. ]);
  47169. };
  47170. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47171. if (this._onLostFocus) {
  47172. BABYLON.Tools.UnregisterTopRootEvents([
  47173. { name: "blur", handler: this._onLostFocus }
  47174. ]);
  47175. }
  47176. if (element && this._observer) {
  47177. this.camera.getScene().onPointerObservable.remove(this._observer);
  47178. this._observer = null;
  47179. if (this._onContextMenu) {
  47180. element.removeEventListener("contextmenu", this._onContextMenu);
  47181. }
  47182. if (this._onMouseMove) {
  47183. element.removeEventListener("mousemove", this._onMouseMove);
  47184. }
  47185. if (this._onGestureStart) {
  47186. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47187. }
  47188. if (this._onGesture) {
  47189. element.removeEventListener("MSGestureChange", this._onGesture);
  47190. }
  47191. this._isPanClick = false;
  47192. this.pinchInwards = true;
  47193. this._onMouseMove = null;
  47194. this._onGestureStart = null;
  47195. this._onGesture = null;
  47196. this._MSGestureHandler = null;
  47197. this._onLostFocus = null;
  47198. this._onContextMenu = null;
  47199. }
  47200. };
  47201. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47202. return "ArcRotateCameraPointersInput";
  47203. };
  47204. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47205. return "pointers";
  47206. };
  47207. __decorate([
  47208. BABYLON.serialize()
  47209. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47210. __decorate([
  47211. BABYLON.serialize()
  47212. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47213. __decorate([
  47214. BABYLON.serialize()
  47215. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47216. __decorate([
  47217. BABYLON.serialize()
  47218. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47219. __decorate([
  47220. BABYLON.serialize()
  47221. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47222. __decorate([
  47223. BABYLON.serialize()
  47224. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47225. __decorate([
  47226. BABYLON.serialize()
  47227. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47228. __decorate([
  47229. BABYLON.serialize()
  47230. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47231. return ArcRotateCameraPointersInput;
  47232. }());
  47233. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47234. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47235. })(BABYLON || (BABYLON = {}));
  47236. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47237. var BABYLON;
  47238. (function (BABYLON) {
  47239. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47240. __extends(ArcRotateCameraInputsManager, _super);
  47241. function ArcRotateCameraInputsManager(camera) {
  47242. return _super.call(this, camera) || this;
  47243. }
  47244. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47245. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47246. return this;
  47247. };
  47248. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47249. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47250. return this;
  47251. };
  47252. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47253. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47254. return this;
  47255. };
  47256. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47257. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47258. return this;
  47259. };
  47260. return ArcRotateCameraInputsManager;
  47261. }(BABYLON.CameraInputsManager));
  47262. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47263. })(BABYLON || (BABYLON = {}));
  47264. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47265. var BABYLON;
  47266. (function (BABYLON) {
  47267. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47268. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47269. });
  47270. var ArcRotateCamera = /** @class */ (function (_super) {
  47271. __extends(ArcRotateCamera, _super);
  47272. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47273. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47274. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47275. _this.inertialAlphaOffset = 0;
  47276. _this.inertialBetaOffset = 0;
  47277. _this.inertialRadiusOffset = 0;
  47278. _this.lowerAlphaLimit = null;
  47279. _this.upperAlphaLimit = null;
  47280. _this.lowerBetaLimit = 0.01;
  47281. _this.upperBetaLimit = Math.PI;
  47282. _this.lowerRadiusLimit = null;
  47283. _this.upperRadiusLimit = null;
  47284. _this.inertialPanningX = 0;
  47285. _this.inertialPanningY = 0;
  47286. _this.pinchToPanMaxDistance = 20;
  47287. _this.panningDistanceLimit = null;
  47288. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47289. _this.panningInertia = 0.9;
  47290. //-- end properties for backward compatibility for inputs
  47291. _this.zoomOnFactor = 1;
  47292. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47293. _this.allowUpsideDown = true;
  47294. _this._viewMatrix = new BABYLON.Matrix();
  47295. // Panning
  47296. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47297. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47298. _this.checkCollisions = false;
  47299. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47300. _this._previousPosition = BABYLON.Vector3.Zero();
  47301. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47302. _this._newPosition = BABYLON.Vector3.Zero();
  47303. _this._computationVector = BABYLON.Vector3.Zero();
  47304. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47305. if (collidedMesh === void 0) { collidedMesh = null; }
  47306. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47307. newPosition.multiplyInPlace(_this._collider._radius);
  47308. }
  47309. if (!collidedMesh) {
  47310. _this._previousPosition.copyFrom(_this.position);
  47311. }
  47312. else {
  47313. _this.setPosition(newPosition);
  47314. if (_this.onCollide) {
  47315. _this.onCollide(collidedMesh);
  47316. }
  47317. }
  47318. // Recompute because of constraints
  47319. var cosa = Math.cos(_this.alpha);
  47320. var sina = Math.sin(_this.alpha);
  47321. var cosb = Math.cos(_this.beta);
  47322. var sinb = Math.sin(_this.beta);
  47323. if (sinb === 0) {
  47324. sinb = 0.0001;
  47325. }
  47326. var target = _this._getTargetPosition();
  47327. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47328. target.addToRef(_this._computationVector, _this._newPosition);
  47329. _this.position.copyFrom(_this._newPosition);
  47330. var up = _this.upVector;
  47331. if (_this.allowUpsideDown && _this.beta < 0) {
  47332. up = up.clone();
  47333. up = up.negate();
  47334. }
  47335. _this._computeViewMatrix(_this.position, target, up);
  47336. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47337. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47338. _this._collisionTriggered = false;
  47339. };
  47340. _this._target = BABYLON.Vector3.Zero();
  47341. if (target) {
  47342. _this.setTarget(target);
  47343. }
  47344. _this.alpha = alpha;
  47345. _this.beta = beta;
  47346. _this.radius = radius;
  47347. _this.getViewMatrix();
  47348. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47349. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47350. return _this;
  47351. }
  47352. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47353. get: function () {
  47354. return this._target;
  47355. },
  47356. set: function (value) {
  47357. this.setTarget(value);
  47358. },
  47359. enumerable: true,
  47360. configurable: true
  47361. });
  47362. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47363. //-- begin properties for backward compatibility for inputs
  47364. get: function () {
  47365. var pointers = this.inputs.attached["pointers"];
  47366. if (pointers)
  47367. return pointers.angularSensibilityX;
  47368. return 0;
  47369. },
  47370. set: function (value) {
  47371. var pointers = this.inputs.attached["pointers"];
  47372. if (pointers) {
  47373. pointers.angularSensibilityX = value;
  47374. }
  47375. },
  47376. enumerable: true,
  47377. configurable: true
  47378. });
  47379. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47380. get: function () {
  47381. var pointers = this.inputs.attached["pointers"];
  47382. if (pointers)
  47383. return pointers.angularSensibilityY;
  47384. return 0;
  47385. },
  47386. set: function (value) {
  47387. var pointers = this.inputs.attached["pointers"];
  47388. if (pointers) {
  47389. pointers.angularSensibilityY = value;
  47390. }
  47391. },
  47392. enumerable: true,
  47393. configurable: true
  47394. });
  47395. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47396. get: function () {
  47397. var pointers = this.inputs.attached["pointers"];
  47398. if (pointers)
  47399. return pointers.pinchPrecision;
  47400. return 0;
  47401. },
  47402. set: function (value) {
  47403. var pointers = this.inputs.attached["pointers"];
  47404. if (pointers) {
  47405. pointers.pinchPrecision = value;
  47406. }
  47407. },
  47408. enumerable: true,
  47409. configurable: true
  47410. });
  47411. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47412. get: function () {
  47413. var pointers = this.inputs.attached["pointers"];
  47414. if (pointers)
  47415. return pointers.pinchDeltaPercentage;
  47416. return 0;
  47417. },
  47418. set: function (value) {
  47419. var pointers = this.inputs.attached["pointers"];
  47420. if (pointers) {
  47421. pointers.pinchDeltaPercentage = value;
  47422. }
  47423. },
  47424. enumerable: true,
  47425. configurable: true
  47426. });
  47427. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47428. get: function () {
  47429. var pointers = this.inputs.attached["pointers"];
  47430. if (pointers)
  47431. return pointers.panningSensibility;
  47432. return 0;
  47433. },
  47434. set: function (value) {
  47435. var pointers = this.inputs.attached["pointers"];
  47436. if (pointers) {
  47437. pointers.panningSensibility = value;
  47438. }
  47439. },
  47440. enumerable: true,
  47441. configurable: true
  47442. });
  47443. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47444. get: function () {
  47445. var keyboard = this.inputs.attached["keyboard"];
  47446. if (keyboard)
  47447. return keyboard.keysUp;
  47448. return [];
  47449. },
  47450. set: function (value) {
  47451. var keyboard = this.inputs.attached["keyboard"];
  47452. if (keyboard)
  47453. keyboard.keysUp = value;
  47454. },
  47455. enumerable: true,
  47456. configurable: true
  47457. });
  47458. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47459. get: function () {
  47460. var keyboard = this.inputs.attached["keyboard"];
  47461. if (keyboard)
  47462. return keyboard.keysDown;
  47463. return [];
  47464. },
  47465. set: function (value) {
  47466. var keyboard = this.inputs.attached["keyboard"];
  47467. if (keyboard)
  47468. keyboard.keysDown = value;
  47469. },
  47470. enumerable: true,
  47471. configurable: true
  47472. });
  47473. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47474. get: function () {
  47475. var keyboard = this.inputs.attached["keyboard"];
  47476. if (keyboard)
  47477. return keyboard.keysLeft;
  47478. return [];
  47479. },
  47480. set: function (value) {
  47481. var keyboard = this.inputs.attached["keyboard"];
  47482. if (keyboard)
  47483. keyboard.keysLeft = value;
  47484. },
  47485. enumerable: true,
  47486. configurable: true
  47487. });
  47488. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47489. get: function () {
  47490. var keyboard = this.inputs.attached["keyboard"];
  47491. if (keyboard)
  47492. return keyboard.keysRight;
  47493. return [];
  47494. },
  47495. set: function (value) {
  47496. var keyboard = this.inputs.attached["keyboard"];
  47497. if (keyboard)
  47498. keyboard.keysRight = value;
  47499. },
  47500. enumerable: true,
  47501. configurable: true
  47502. });
  47503. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47504. get: function () {
  47505. var mousewheel = this.inputs.attached["mousewheel"];
  47506. if (mousewheel)
  47507. return mousewheel.wheelPrecision;
  47508. return 0;
  47509. },
  47510. set: function (value) {
  47511. var mousewheel = this.inputs.attached["mousewheel"];
  47512. if (mousewheel)
  47513. mousewheel.wheelPrecision = value;
  47514. },
  47515. enumerable: true,
  47516. configurable: true
  47517. });
  47518. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47519. get: function () {
  47520. var mousewheel = this.inputs.attached["mousewheel"];
  47521. if (mousewheel)
  47522. return mousewheel.wheelDeltaPercentage;
  47523. return 0;
  47524. },
  47525. set: function (value) {
  47526. var mousewheel = this.inputs.attached["mousewheel"];
  47527. if (mousewheel)
  47528. mousewheel.wheelDeltaPercentage = value;
  47529. },
  47530. enumerable: true,
  47531. configurable: true
  47532. });
  47533. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47534. get: function () {
  47535. return this._bouncingBehavior;
  47536. },
  47537. enumerable: true,
  47538. configurable: true
  47539. });
  47540. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47541. get: function () {
  47542. return this._bouncingBehavior != null;
  47543. },
  47544. set: function (value) {
  47545. if (value === this.useBouncingBehavior) {
  47546. return;
  47547. }
  47548. if (value) {
  47549. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47550. this.addBehavior(this._bouncingBehavior);
  47551. }
  47552. else if (this._bouncingBehavior) {
  47553. this.removeBehavior(this._bouncingBehavior);
  47554. this._bouncingBehavior = null;
  47555. }
  47556. },
  47557. enumerable: true,
  47558. configurable: true
  47559. });
  47560. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47561. get: function () {
  47562. return this._framingBehavior;
  47563. },
  47564. enumerable: true,
  47565. configurable: true
  47566. });
  47567. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47568. get: function () {
  47569. return this._framingBehavior != null;
  47570. },
  47571. set: function (value) {
  47572. if (value === this.useFramingBehavior) {
  47573. return;
  47574. }
  47575. if (value) {
  47576. this._framingBehavior = new BABYLON.FramingBehavior();
  47577. this.addBehavior(this._framingBehavior);
  47578. }
  47579. else if (this._framingBehavior) {
  47580. this.removeBehavior(this._framingBehavior);
  47581. this._framingBehavior = null;
  47582. }
  47583. },
  47584. enumerable: true,
  47585. configurable: true
  47586. });
  47587. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47588. get: function () {
  47589. return this._autoRotationBehavior;
  47590. },
  47591. enumerable: true,
  47592. configurable: true
  47593. });
  47594. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47595. get: function () {
  47596. return this._autoRotationBehavior != null;
  47597. },
  47598. set: function (value) {
  47599. if (value === this.useAutoRotationBehavior) {
  47600. return;
  47601. }
  47602. if (value) {
  47603. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47604. this.addBehavior(this._autoRotationBehavior);
  47605. }
  47606. else if (this._autoRotationBehavior) {
  47607. this.removeBehavior(this._autoRotationBehavior);
  47608. this._autoRotationBehavior = null;
  47609. }
  47610. },
  47611. enumerable: true,
  47612. configurable: true
  47613. });
  47614. // Cache
  47615. ArcRotateCamera.prototype._initCache = function () {
  47616. _super.prototype._initCache.call(this);
  47617. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47618. this._cache.alpha = undefined;
  47619. this._cache.beta = undefined;
  47620. this._cache.radius = undefined;
  47621. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47622. };
  47623. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47624. if (!ignoreParentClass) {
  47625. _super.prototype._updateCache.call(this);
  47626. }
  47627. this._cache._target.copyFrom(this._getTargetPosition());
  47628. this._cache.alpha = this.alpha;
  47629. this._cache.beta = this.beta;
  47630. this._cache.radius = this.radius;
  47631. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47632. };
  47633. ArcRotateCamera.prototype._getTargetPosition = function () {
  47634. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47635. var pos = this._targetHost.getAbsolutePosition();
  47636. if (this._targetBoundingCenter) {
  47637. pos.addToRef(this._targetBoundingCenter, this._target);
  47638. }
  47639. else {
  47640. this._target.copyFrom(pos);
  47641. }
  47642. }
  47643. var lockedTargetPosition = this._getLockedTargetPosition();
  47644. if (lockedTargetPosition) {
  47645. return lockedTargetPosition;
  47646. }
  47647. return this._target;
  47648. };
  47649. ArcRotateCamera.prototype.storeState = function () {
  47650. this._storedAlpha = this.alpha;
  47651. this._storedBeta = this.beta;
  47652. this._storedRadius = this.radius;
  47653. this._storedTarget = this._getTargetPosition().clone();
  47654. return _super.prototype.storeState.call(this);
  47655. };
  47656. /**
  47657. * Restored camera state. You must call storeState() first
  47658. */
  47659. ArcRotateCamera.prototype._restoreStateValues = function () {
  47660. if (!_super.prototype._restoreStateValues.call(this)) {
  47661. return false;
  47662. }
  47663. this.alpha = this._storedAlpha;
  47664. this.beta = this._storedBeta;
  47665. this.radius = this._storedRadius;
  47666. this.setTarget(this._storedTarget.clone());
  47667. this.inertialAlphaOffset = 0;
  47668. this.inertialBetaOffset = 0;
  47669. this.inertialRadiusOffset = 0;
  47670. this.inertialPanningX = 0;
  47671. this.inertialPanningY = 0;
  47672. return true;
  47673. };
  47674. // Synchronized
  47675. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47676. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47677. return false;
  47678. return this._cache._target.equals(this._getTargetPosition())
  47679. && this._cache.alpha === this.alpha
  47680. && this._cache.beta === this.beta
  47681. && this._cache.radius === this.radius
  47682. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47683. };
  47684. // Methods
  47685. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47686. var _this = this;
  47687. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47688. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47689. this._useCtrlForPanning = useCtrlForPanning;
  47690. this._panningMouseButton = panningMouseButton;
  47691. this.inputs.attachElement(element, noPreventDefault);
  47692. this._reset = function () {
  47693. _this.inertialAlphaOffset = 0;
  47694. _this.inertialBetaOffset = 0;
  47695. _this.inertialRadiusOffset = 0;
  47696. _this.inertialPanningX = 0;
  47697. _this.inertialPanningY = 0;
  47698. };
  47699. };
  47700. ArcRotateCamera.prototype.detachControl = function (element) {
  47701. this.inputs.detachElement(element);
  47702. if (this._reset) {
  47703. this._reset();
  47704. }
  47705. };
  47706. ArcRotateCamera.prototype._checkInputs = function () {
  47707. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47708. if (this._collisionTriggered) {
  47709. return;
  47710. }
  47711. this.inputs.checkInputs();
  47712. // Inertia
  47713. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47714. var inertialAlphaOffset = this.inertialAlphaOffset;
  47715. if (this.beta <= 0)
  47716. inertialAlphaOffset *= -1;
  47717. if (this.getScene().useRightHandedSystem)
  47718. inertialAlphaOffset *= -1;
  47719. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47720. inertialAlphaOffset *= -1;
  47721. this.alpha += inertialAlphaOffset;
  47722. this.beta += this.inertialBetaOffset;
  47723. this.radius -= this.inertialRadiusOffset;
  47724. this.inertialAlphaOffset *= this.inertia;
  47725. this.inertialBetaOffset *= this.inertia;
  47726. this.inertialRadiusOffset *= this.inertia;
  47727. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47728. this.inertialAlphaOffset = 0;
  47729. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47730. this.inertialBetaOffset = 0;
  47731. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47732. this.inertialRadiusOffset = 0;
  47733. }
  47734. // Panning inertia
  47735. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47736. if (!this._localDirection) {
  47737. this._localDirection = BABYLON.Vector3.Zero();
  47738. this._transformedDirection = BABYLON.Vector3.Zero();
  47739. }
  47740. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47741. this._localDirection.multiplyInPlace(this.panningAxis);
  47742. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47743. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47744. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47745. if (!this.panningAxis.y) {
  47746. this._transformedDirection.y = 0;
  47747. }
  47748. if (!this._targetHost) {
  47749. if (this.panningDistanceLimit) {
  47750. this._transformedDirection.addInPlace(this._target);
  47751. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47752. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47753. this._target.copyFrom(this._transformedDirection);
  47754. }
  47755. }
  47756. else {
  47757. this._target.addInPlace(this._transformedDirection);
  47758. }
  47759. }
  47760. this.inertialPanningX *= this.panningInertia;
  47761. this.inertialPanningY *= this.panningInertia;
  47762. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47763. this.inertialPanningX = 0;
  47764. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47765. this.inertialPanningY = 0;
  47766. }
  47767. // Limits
  47768. this._checkLimits();
  47769. _super.prototype._checkInputs.call(this);
  47770. };
  47771. ArcRotateCamera.prototype._checkLimits = function () {
  47772. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47773. if (this.allowUpsideDown && this.beta > Math.PI) {
  47774. this.beta = this.beta - (2 * Math.PI);
  47775. }
  47776. }
  47777. else {
  47778. if (this.beta < this.lowerBetaLimit) {
  47779. this.beta = this.lowerBetaLimit;
  47780. }
  47781. }
  47782. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47783. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47784. this.beta = this.beta + (2 * Math.PI);
  47785. }
  47786. }
  47787. else {
  47788. if (this.beta > this.upperBetaLimit) {
  47789. this.beta = this.upperBetaLimit;
  47790. }
  47791. }
  47792. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  47793. this.alpha = this.lowerAlphaLimit;
  47794. }
  47795. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  47796. this.alpha = this.upperAlphaLimit;
  47797. }
  47798. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  47799. this.radius = this.lowerRadiusLimit;
  47800. }
  47801. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  47802. this.radius = this.upperRadiusLimit;
  47803. }
  47804. };
  47805. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47806. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47807. this.radius = this._computationVector.length();
  47808. if (this.radius === 0) {
  47809. this.radius = 0.0001; // Just to avoid division by zero
  47810. }
  47811. // Alpha
  47812. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47813. if (this._computationVector.z < 0) {
  47814. this.alpha = 2 * Math.PI - this.alpha;
  47815. }
  47816. // Beta
  47817. this.beta = Math.acos(this._computationVector.y / this.radius);
  47818. this._checkLimits();
  47819. };
  47820. ArcRotateCamera.prototype.setPosition = function (position) {
  47821. if (this.position.equals(position)) {
  47822. return;
  47823. }
  47824. this.position.copyFrom(position);
  47825. this.rebuildAnglesAndRadius();
  47826. };
  47827. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47828. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47829. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47830. if (target.getBoundingInfo) {
  47831. if (toBoundingCenter) {
  47832. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47833. }
  47834. else {
  47835. this._targetBoundingCenter = null;
  47836. }
  47837. this._targetHost = target;
  47838. this._target = this._getTargetPosition();
  47839. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47840. }
  47841. else {
  47842. var newTarget = target;
  47843. var currentTarget = this._getTargetPosition();
  47844. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47845. return;
  47846. }
  47847. this._targetHost = null;
  47848. this._target = newTarget;
  47849. this._targetBoundingCenter = null;
  47850. this.onMeshTargetChangedObservable.notifyObservers(null);
  47851. }
  47852. this.rebuildAnglesAndRadius();
  47853. };
  47854. ArcRotateCamera.prototype._getViewMatrix = function () {
  47855. // Compute
  47856. var cosa = Math.cos(this.alpha);
  47857. var sina = Math.sin(this.alpha);
  47858. var cosb = Math.cos(this.beta);
  47859. var sinb = Math.sin(this.beta);
  47860. if (sinb === 0) {
  47861. sinb = 0.0001;
  47862. }
  47863. var target = this._getTargetPosition();
  47864. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47865. target.addToRef(this._computationVector, this._newPosition);
  47866. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47867. if (!this._collider) {
  47868. this._collider = new BABYLON.Collider();
  47869. }
  47870. this._collider._radius = this.collisionRadius;
  47871. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47872. this._collisionTriggered = true;
  47873. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47874. }
  47875. else {
  47876. this.position.copyFrom(this._newPosition);
  47877. var up = this.upVector;
  47878. if (this.allowUpsideDown && sinb < 0) {
  47879. up = up.clone();
  47880. up = up.negate();
  47881. }
  47882. this._computeViewMatrix(this.position, target, up);
  47883. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47884. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47885. }
  47886. this._currentTarget = target;
  47887. return this._viewMatrix;
  47888. };
  47889. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47890. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47891. meshes = meshes || this.getScene().meshes;
  47892. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47893. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47894. this.radius = distance * this.zoomOnFactor;
  47895. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47896. };
  47897. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47898. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47899. var meshesOrMinMaxVector;
  47900. var distance;
  47901. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47902. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47903. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47904. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47905. }
  47906. else { //minMaxVector and distance
  47907. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47908. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47909. distance = minMaxVectorAndDistance.distance;
  47910. }
  47911. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47912. if (!doNotUpdateMaxZ) {
  47913. this.maxZ = distance * 2;
  47914. }
  47915. };
  47916. /**
  47917. * @override
  47918. * Override Camera.createRigCamera
  47919. */
  47920. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47921. var alphaShift = 0;
  47922. switch (this.cameraRigMode) {
  47923. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47924. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47925. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47926. case BABYLON.Camera.RIG_MODE_VR:
  47927. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47928. break;
  47929. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47930. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47931. break;
  47932. }
  47933. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47934. rigCam._cameraRigParams = {};
  47935. return rigCam;
  47936. };
  47937. /**
  47938. * @override
  47939. * Override Camera._updateRigCameras
  47940. */
  47941. ArcRotateCamera.prototype._updateRigCameras = function () {
  47942. var camLeft = this._rigCameras[0];
  47943. var camRight = this._rigCameras[1];
  47944. camLeft.beta = camRight.beta = this.beta;
  47945. camLeft.radius = camRight.radius = this.radius;
  47946. switch (this.cameraRigMode) {
  47947. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47948. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47949. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47950. case BABYLON.Camera.RIG_MODE_VR:
  47951. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47952. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47953. break;
  47954. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47955. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47956. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47957. break;
  47958. }
  47959. _super.prototype._updateRigCameras.call(this);
  47960. };
  47961. ArcRotateCamera.prototype.dispose = function () {
  47962. this.inputs.clear();
  47963. _super.prototype.dispose.call(this);
  47964. };
  47965. ArcRotateCamera.prototype.getClassName = function () {
  47966. return "ArcRotateCamera";
  47967. };
  47968. __decorate([
  47969. BABYLON.serialize()
  47970. ], ArcRotateCamera.prototype, "alpha", void 0);
  47971. __decorate([
  47972. BABYLON.serialize()
  47973. ], ArcRotateCamera.prototype, "beta", void 0);
  47974. __decorate([
  47975. BABYLON.serialize()
  47976. ], ArcRotateCamera.prototype, "radius", void 0);
  47977. __decorate([
  47978. BABYLON.serializeAsVector3("target")
  47979. ], ArcRotateCamera.prototype, "_target", void 0);
  47980. __decorate([
  47981. BABYLON.serialize()
  47982. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  47983. __decorate([
  47984. BABYLON.serialize()
  47985. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  47986. __decorate([
  47987. BABYLON.serialize()
  47988. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  47989. __decorate([
  47990. BABYLON.serialize()
  47991. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  47992. __decorate([
  47993. BABYLON.serialize()
  47994. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  47995. __decorate([
  47996. BABYLON.serialize()
  47997. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  47998. __decorate([
  47999. BABYLON.serialize()
  48000. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48001. __decorate([
  48002. BABYLON.serialize()
  48003. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48004. __decorate([
  48005. BABYLON.serialize()
  48006. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48007. __decorate([
  48008. BABYLON.serialize()
  48009. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48010. __decorate([
  48011. BABYLON.serialize()
  48012. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48013. __decorate([
  48014. BABYLON.serialize()
  48015. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48016. __decorate([
  48017. BABYLON.serialize()
  48018. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48019. __decorate([
  48020. BABYLON.serializeAsVector3()
  48021. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48022. __decorate([
  48023. BABYLON.serialize()
  48024. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48025. __decorate([
  48026. BABYLON.serialize()
  48027. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48028. __decorate([
  48029. BABYLON.serialize()
  48030. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48031. return ArcRotateCamera;
  48032. }(BABYLON.TargetCamera));
  48033. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48034. })(BABYLON || (BABYLON = {}));
  48035. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48036. var BABYLON;
  48037. (function (BABYLON) {
  48038. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48039. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48040. });
  48041. /**
  48042. * The HemisphericLight simulates the ambient environment light,
  48043. * so the passed direction is the light reflection direction, not the incoming direction.
  48044. */
  48045. var HemisphericLight = /** @class */ (function (_super) {
  48046. __extends(HemisphericLight, _super);
  48047. /**
  48048. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48049. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48050. * The HemisphericLight can't cast shadows.
  48051. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48052. * @param name The friendly name of the light
  48053. * @param direction The direction of the light reflection
  48054. * @param scene The scene the light belongs to
  48055. */
  48056. function HemisphericLight(name, direction, scene) {
  48057. var _this = _super.call(this, name, scene) || this;
  48058. /**
  48059. * The groundColor is the light in the opposite direction to the one specified during creation.
  48060. * 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.
  48061. */
  48062. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48063. _this.direction = direction || BABYLON.Vector3.Up();
  48064. return _this;
  48065. }
  48066. HemisphericLight.prototype._buildUniformLayout = function () {
  48067. this._uniformBuffer.addUniform("vLightData", 4);
  48068. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48069. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48070. this._uniformBuffer.addUniform("vLightGround", 3);
  48071. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48072. this._uniformBuffer.addUniform("depthValues", 2);
  48073. this._uniformBuffer.create();
  48074. };
  48075. /**
  48076. * Returns the string "HemisphericLight".
  48077. * @return The class name
  48078. */
  48079. HemisphericLight.prototype.getClassName = function () {
  48080. return "HemisphericLight";
  48081. };
  48082. /**
  48083. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48084. * Returns the updated direction.
  48085. * @param target The target the direction should point to
  48086. * @return The computed direction
  48087. */
  48088. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48089. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48090. return this.direction;
  48091. };
  48092. /**
  48093. * Returns the shadow generator associated to the light.
  48094. * @returns Always null for hemispheric lights because it does not support shadows.
  48095. */
  48096. HemisphericLight.prototype.getShadowGenerator = function () {
  48097. return null;
  48098. };
  48099. /**
  48100. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48101. * @param effect The effect to update
  48102. * @param lightIndex The index of the light in the effect to update
  48103. * @returns The hemispheric light
  48104. */
  48105. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48106. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48107. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48108. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48109. return this;
  48110. };
  48111. /**
  48112. * @hidden internal use only.
  48113. */
  48114. HemisphericLight.prototype._getWorldMatrix = function () {
  48115. if (!this._worldMatrix) {
  48116. this._worldMatrix = BABYLON.Matrix.Identity();
  48117. }
  48118. return this._worldMatrix;
  48119. };
  48120. /**
  48121. * Returns the integer 3.
  48122. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48123. */
  48124. HemisphericLight.prototype.getTypeID = function () {
  48125. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48126. };
  48127. /**
  48128. * Prepares the list of defines specific to the light type.
  48129. * @param defines the list of defines
  48130. * @param lightIndex defines the index of the light for the effect
  48131. */
  48132. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48133. defines["HEMILIGHT" + lightIndex] = true;
  48134. };
  48135. __decorate([
  48136. BABYLON.serializeAsColor3()
  48137. ], HemisphericLight.prototype, "groundColor", void 0);
  48138. __decorate([
  48139. BABYLON.serializeAsVector3()
  48140. ], HemisphericLight.prototype, "direction", void 0);
  48141. return HemisphericLight;
  48142. }(BABYLON.Light));
  48143. BABYLON.HemisphericLight = HemisphericLight;
  48144. })(BABYLON || (BABYLON = {}));
  48145. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48146. var BABYLON;
  48147. (function (BABYLON) {
  48148. /**
  48149. * Base implementation IShadowLight
  48150. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48151. */
  48152. var ShadowLight = /** @class */ (function (_super) {
  48153. __extends(ShadowLight, _super);
  48154. function ShadowLight() {
  48155. var _this = _super !== null && _super.apply(this, arguments) || this;
  48156. _this._needProjectionMatrixCompute = true;
  48157. return _this;
  48158. }
  48159. ShadowLight.prototype._setPosition = function (value) {
  48160. this._position = value;
  48161. };
  48162. Object.defineProperty(ShadowLight.prototype, "position", {
  48163. /**
  48164. * Sets the position the shadow will be casted from. Also use as the light position for both
  48165. * point and spot lights.
  48166. */
  48167. get: function () {
  48168. return this._position;
  48169. },
  48170. /**
  48171. * Sets the position the shadow will be casted from. Also use as the light position for both
  48172. * point and spot lights.
  48173. */
  48174. set: function (value) {
  48175. this._setPosition(value);
  48176. },
  48177. enumerable: true,
  48178. configurable: true
  48179. });
  48180. ShadowLight.prototype._setDirection = function (value) {
  48181. this._direction = value;
  48182. };
  48183. Object.defineProperty(ShadowLight.prototype, "direction", {
  48184. /**
  48185. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48186. * Also use as the light direction on spot and directional lights.
  48187. */
  48188. get: function () {
  48189. return this._direction;
  48190. },
  48191. /**
  48192. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48193. * Also use as the light direction on spot and directional lights.
  48194. */
  48195. set: function (value) {
  48196. this._setDirection(value);
  48197. },
  48198. enumerable: true,
  48199. configurable: true
  48200. });
  48201. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48202. /**
  48203. * Gets the shadow projection clipping minimum z value.
  48204. */
  48205. get: function () {
  48206. return this._shadowMinZ;
  48207. },
  48208. /**
  48209. * Sets the shadow projection clipping minimum z value.
  48210. */
  48211. set: function (value) {
  48212. this._shadowMinZ = value;
  48213. this.forceProjectionMatrixCompute();
  48214. },
  48215. enumerable: true,
  48216. configurable: true
  48217. });
  48218. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48219. /**
  48220. * Sets the shadow projection clipping maximum z value.
  48221. */
  48222. get: function () {
  48223. return this._shadowMaxZ;
  48224. },
  48225. /**
  48226. * Gets the shadow projection clipping maximum z value.
  48227. */
  48228. set: function (value) {
  48229. this._shadowMaxZ = value;
  48230. this.forceProjectionMatrixCompute();
  48231. },
  48232. enumerable: true,
  48233. configurable: true
  48234. });
  48235. /**
  48236. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48237. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48238. */
  48239. ShadowLight.prototype.computeTransformedInformation = function () {
  48240. if (this.parent && this.parent.getWorldMatrix) {
  48241. if (!this.transformedPosition) {
  48242. this.transformedPosition = BABYLON.Vector3.Zero();
  48243. }
  48244. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48245. // In case the direction is present.
  48246. if (this.direction) {
  48247. if (!this.transformedDirection) {
  48248. this.transformedDirection = BABYLON.Vector3.Zero();
  48249. }
  48250. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48251. }
  48252. return true;
  48253. }
  48254. return false;
  48255. };
  48256. /**
  48257. * Return the depth scale used for the shadow map.
  48258. * @returns the depth scale.
  48259. */
  48260. ShadowLight.prototype.getDepthScale = function () {
  48261. return 50.0;
  48262. };
  48263. /**
  48264. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48265. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48266. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48267. */
  48268. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48269. return this.transformedDirection ? this.transformedDirection : this.direction;
  48270. };
  48271. /**
  48272. * Returns the ShadowLight absolute position in the World.
  48273. * @returns the position vector in world space
  48274. */
  48275. ShadowLight.prototype.getAbsolutePosition = function () {
  48276. return this.transformedPosition ? this.transformedPosition : this.position;
  48277. };
  48278. /**
  48279. * Sets the ShadowLight direction toward the passed target.
  48280. * @param target The point tot target in local space
  48281. * @returns the updated ShadowLight direction
  48282. */
  48283. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48284. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48285. return this.direction;
  48286. };
  48287. /**
  48288. * Returns the light rotation in euler definition.
  48289. * @returns the x y z rotation in local space.
  48290. */
  48291. ShadowLight.prototype.getRotation = function () {
  48292. this.direction.normalize();
  48293. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48294. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48295. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48296. };
  48297. /**
  48298. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48299. * @returns true if a cube texture needs to be use
  48300. */
  48301. ShadowLight.prototype.needCube = function () {
  48302. return false;
  48303. };
  48304. /**
  48305. * Detects if the projection matrix requires to be recomputed this frame.
  48306. * @returns true if it requires to be recomputed otherwise, false.
  48307. */
  48308. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48309. return this._needProjectionMatrixCompute;
  48310. };
  48311. /**
  48312. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48313. */
  48314. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48315. this._needProjectionMatrixCompute = true;
  48316. };
  48317. /**
  48318. * Get the world matrix of the sahdow lights.
  48319. * @hidden Internal Use Only
  48320. */
  48321. ShadowLight.prototype._getWorldMatrix = function () {
  48322. if (!this._worldMatrix) {
  48323. this._worldMatrix = BABYLON.Matrix.Identity();
  48324. }
  48325. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48326. return this._worldMatrix;
  48327. };
  48328. /**
  48329. * Gets the minZ used for shadow according to both the scene and the light.
  48330. * @param activeCamera The camera we are returning the min for
  48331. * @returns the depth min z
  48332. */
  48333. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48334. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48335. };
  48336. /**
  48337. * Gets the maxZ used for shadow according to both the scene and the light.
  48338. * @param activeCamera The camera we are returning the max for
  48339. * @returns the depth max z
  48340. */
  48341. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48342. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48343. };
  48344. /**
  48345. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48346. * @param matrix The materix to updated with the projection information
  48347. * @param viewMatrix The transform matrix of the light
  48348. * @param renderList The list of mesh to render in the map
  48349. * @returns The current light
  48350. */
  48351. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48352. if (this.customProjectionMatrixBuilder) {
  48353. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48354. }
  48355. else {
  48356. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48357. }
  48358. return this;
  48359. };
  48360. __decorate([
  48361. BABYLON.serializeAsVector3()
  48362. ], ShadowLight.prototype, "position", null);
  48363. __decorate([
  48364. BABYLON.serializeAsVector3()
  48365. ], ShadowLight.prototype, "direction", null);
  48366. __decorate([
  48367. BABYLON.serialize()
  48368. ], ShadowLight.prototype, "shadowMinZ", null);
  48369. __decorate([
  48370. BABYLON.serialize()
  48371. ], ShadowLight.prototype, "shadowMaxZ", null);
  48372. return ShadowLight;
  48373. }(BABYLON.Light));
  48374. BABYLON.ShadowLight = ShadowLight;
  48375. })(BABYLON || (BABYLON = {}));
  48376. //# sourceMappingURL=babylon.shadowLight.js.map
  48377. var BABYLON;
  48378. (function (BABYLON) {
  48379. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48380. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48381. });
  48382. /**
  48383. * A point light is a light defined by an unique point in world space.
  48384. * The light is emitted in every direction from this point.
  48385. * A good example of a point light is a standard light bulb.
  48386. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48387. */
  48388. var PointLight = /** @class */ (function (_super) {
  48389. __extends(PointLight, _super);
  48390. /**
  48391. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48392. * A PointLight emits the light in every direction.
  48393. * It can cast shadows.
  48394. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48395. * ```javascript
  48396. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48397. * ```
  48398. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48399. * @param name The light friendly name
  48400. * @param position The position of the point light in the scene
  48401. * @param scene The scene the lights belongs to
  48402. */
  48403. function PointLight(name, position, scene) {
  48404. var _this = _super.call(this, name, scene) || this;
  48405. _this._shadowAngle = Math.PI / 2;
  48406. _this.position = position;
  48407. return _this;
  48408. }
  48409. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48410. /**
  48411. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48412. * This specifies what angle the shadow will use to be created.
  48413. *
  48414. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48415. */
  48416. get: function () {
  48417. return this._shadowAngle;
  48418. },
  48419. /**
  48420. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48421. * This specifies what angle the shadow will use to be created.
  48422. *
  48423. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48424. */
  48425. set: function (value) {
  48426. this._shadowAngle = value;
  48427. this.forceProjectionMatrixCompute();
  48428. },
  48429. enumerable: true,
  48430. configurable: true
  48431. });
  48432. Object.defineProperty(PointLight.prototype, "direction", {
  48433. /**
  48434. * Gets the direction if it has been set.
  48435. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48436. */
  48437. get: function () {
  48438. return this._direction;
  48439. },
  48440. /**
  48441. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48442. */
  48443. set: function (value) {
  48444. var previousNeedCube = this.needCube();
  48445. this._direction = value;
  48446. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48447. this._shadowGenerator.recreateShadowMap();
  48448. }
  48449. },
  48450. enumerable: true,
  48451. configurable: true
  48452. });
  48453. /**
  48454. * Returns the string "PointLight"
  48455. * @returns the class name
  48456. */
  48457. PointLight.prototype.getClassName = function () {
  48458. return "PointLight";
  48459. };
  48460. /**
  48461. * Returns the integer 0.
  48462. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48463. */
  48464. PointLight.prototype.getTypeID = function () {
  48465. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48466. };
  48467. /**
  48468. * Specifies wether or not the shadowmap should be a cube texture.
  48469. * @returns true if the shadowmap needs to be a cube texture.
  48470. */
  48471. PointLight.prototype.needCube = function () {
  48472. return !this.direction;
  48473. };
  48474. /**
  48475. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48476. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48477. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48478. */
  48479. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48480. if (this.direction) {
  48481. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48482. }
  48483. else {
  48484. switch (faceIndex) {
  48485. case 0:
  48486. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48487. case 1:
  48488. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48489. case 2:
  48490. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48491. case 3:
  48492. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48493. case 4:
  48494. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48495. case 5:
  48496. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48497. }
  48498. }
  48499. return BABYLON.Vector3.Zero();
  48500. };
  48501. /**
  48502. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48503. * - fov = PI / 2
  48504. * - aspect ratio : 1.0
  48505. * - z-near and far equal to the active camera minZ and maxZ.
  48506. * Returns the PointLight.
  48507. */
  48508. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48509. var activeCamera = this.getScene().activeCamera;
  48510. if (!activeCamera) {
  48511. return;
  48512. }
  48513. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48514. };
  48515. PointLight.prototype._buildUniformLayout = function () {
  48516. this._uniformBuffer.addUniform("vLightData", 4);
  48517. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48518. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48519. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48520. this._uniformBuffer.addUniform("depthValues", 2);
  48521. this._uniformBuffer.create();
  48522. };
  48523. /**
  48524. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48525. * @param effect The effect to update
  48526. * @param lightIndex The index of the light in the effect to update
  48527. * @returns The point light
  48528. */
  48529. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48530. if (this.computeTransformedInformation()) {
  48531. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48532. return this;
  48533. }
  48534. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48535. return this;
  48536. };
  48537. /**
  48538. * Prepares the list of defines specific to the light type.
  48539. * @param defines the list of defines
  48540. * @param lightIndex defines the index of the light for the effect
  48541. */
  48542. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48543. defines["POINTLIGHT" + lightIndex] = true;
  48544. };
  48545. __decorate([
  48546. BABYLON.serialize()
  48547. ], PointLight.prototype, "shadowAngle", null);
  48548. return PointLight;
  48549. }(BABYLON.ShadowLight));
  48550. BABYLON.PointLight = PointLight;
  48551. })(BABYLON || (BABYLON = {}));
  48552. //# sourceMappingURL=babylon.pointLight.js.map
  48553. var BABYLON;
  48554. (function (BABYLON) {
  48555. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48556. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48557. });
  48558. /**
  48559. * A directional light is defined by a direction (what a surprise!).
  48560. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48561. * 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.
  48562. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48563. */
  48564. var DirectionalLight = /** @class */ (function (_super) {
  48565. __extends(DirectionalLight, _super);
  48566. /**
  48567. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48568. * The directional light is emitted from everywhere in the given direction.
  48569. * It can cast shawdows.
  48570. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48571. * @param name The friendly name of the light
  48572. * @param direction The direction of the light
  48573. * @param scene The scene the light belongs to
  48574. */
  48575. function DirectionalLight(name, direction, scene) {
  48576. var _this = _super.call(this, name, scene) || this;
  48577. _this._shadowFrustumSize = 0;
  48578. _this._shadowOrthoScale = 0.1;
  48579. /**
  48580. * Automatically compute the projection matrix to best fit (including all the casters)
  48581. * on each frame.
  48582. */
  48583. _this.autoUpdateExtends = true;
  48584. // Cache
  48585. _this._orthoLeft = Number.MAX_VALUE;
  48586. _this._orthoRight = Number.MIN_VALUE;
  48587. _this._orthoTop = Number.MIN_VALUE;
  48588. _this._orthoBottom = Number.MAX_VALUE;
  48589. _this.position = direction.scale(-1.0);
  48590. _this.direction = direction;
  48591. return _this;
  48592. }
  48593. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48594. /**
  48595. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48596. */
  48597. get: function () {
  48598. return this._shadowFrustumSize;
  48599. },
  48600. /**
  48601. * Specifies a fix frustum size for the shadow generation.
  48602. */
  48603. set: function (value) {
  48604. this._shadowFrustumSize = value;
  48605. this.forceProjectionMatrixCompute();
  48606. },
  48607. enumerable: true,
  48608. configurable: true
  48609. });
  48610. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48611. /**
  48612. * Gets the shadow projection scale against the optimal computed one.
  48613. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48614. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48615. */
  48616. get: function () {
  48617. return this._shadowOrthoScale;
  48618. },
  48619. /**
  48620. * Sets the shadow projection scale against the optimal computed one.
  48621. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48622. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48623. */
  48624. set: function (value) {
  48625. this._shadowOrthoScale = value;
  48626. this.forceProjectionMatrixCompute();
  48627. },
  48628. enumerable: true,
  48629. configurable: true
  48630. });
  48631. /**
  48632. * Returns the string "DirectionalLight".
  48633. * @return The class name
  48634. */
  48635. DirectionalLight.prototype.getClassName = function () {
  48636. return "DirectionalLight";
  48637. };
  48638. /**
  48639. * Returns the integer 1.
  48640. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48641. */
  48642. DirectionalLight.prototype.getTypeID = function () {
  48643. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48644. };
  48645. /**
  48646. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48647. * Returns the DirectionalLight Shadow projection matrix.
  48648. */
  48649. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48650. if (this.shadowFrustumSize > 0) {
  48651. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48652. }
  48653. else {
  48654. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48655. }
  48656. };
  48657. /**
  48658. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48659. * Returns the DirectionalLight Shadow projection matrix.
  48660. */
  48661. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48662. var activeCamera = this.getScene().activeCamera;
  48663. if (!activeCamera) {
  48664. return;
  48665. }
  48666. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48667. };
  48668. /**
  48669. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48670. * Returns the DirectionalLight Shadow projection matrix.
  48671. */
  48672. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48673. var activeCamera = this.getScene().activeCamera;
  48674. if (!activeCamera) {
  48675. return;
  48676. }
  48677. // Check extends
  48678. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48679. var tempVector3 = BABYLON.Vector3.Zero();
  48680. this._orthoLeft = Number.MAX_VALUE;
  48681. this._orthoRight = Number.MIN_VALUE;
  48682. this._orthoTop = Number.MIN_VALUE;
  48683. this._orthoBottom = Number.MAX_VALUE;
  48684. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48685. var mesh = renderList[meshIndex];
  48686. if (!mesh) {
  48687. continue;
  48688. }
  48689. var boundingInfo = mesh.getBoundingInfo();
  48690. var boundingBox = boundingInfo.boundingBox;
  48691. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48692. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48693. if (tempVector3.x < this._orthoLeft)
  48694. this._orthoLeft = tempVector3.x;
  48695. if (tempVector3.y < this._orthoBottom)
  48696. this._orthoBottom = tempVector3.y;
  48697. if (tempVector3.x > this._orthoRight)
  48698. this._orthoRight = tempVector3.x;
  48699. if (tempVector3.y > this._orthoTop)
  48700. this._orthoTop = tempVector3.y;
  48701. }
  48702. }
  48703. }
  48704. var xOffset = this._orthoRight - this._orthoLeft;
  48705. var yOffset = this._orthoTop - this._orthoBottom;
  48706. 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);
  48707. };
  48708. DirectionalLight.prototype._buildUniformLayout = function () {
  48709. this._uniformBuffer.addUniform("vLightData", 4);
  48710. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48711. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48712. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48713. this._uniformBuffer.addUniform("depthValues", 2);
  48714. this._uniformBuffer.create();
  48715. };
  48716. /**
  48717. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48718. * @param effect The effect to update
  48719. * @param lightIndex The index of the light in the effect to update
  48720. * @returns The directional light
  48721. */
  48722. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48723. if (this.computeTransformedInformation()) {
  48724. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48725. return this;
  48726. }
  48727. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48728. return this;
  48729. };
  48730. /**
  48731. * Gets the minZ used for shadow according to both the scene and the light.
  48732. *
  48733. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48734. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48735. * @param activeCamera The camera we are returning the min for
  48736. * @returns the depth min z
  48737. */
  48738. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48739. return 1;
  48740. };
  48741. /**
  48742. * Gets the maxZ used for shadow according to both the scene and the light.
  48743. *
  48744. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48745. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48746. * @param activeCamera The camera we are returning the max for
  48747. * @returns the depth max z
  48748. */
  48749. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48750. return 1;
  48751. };
  48752. /**
  48753. * Prepares the list of defines specific to the light type.
  48754. * @param defines the list of defines
  48755. * @param lightIndex defines the index of the light for the effect
  48756. */
  48757. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48758. defines["DIRLIGHT" + lightIndex] = true;
  48759. };
  48760. __decorate([
  48761. BABYLON.serialize()
  48762. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48763. __decorate([
  48764. BABYLON.serialize()
  48765. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48766. __decorate([
  48767. BABYLON.serialize()
  48768. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48769. return DirectionalLight;
  48770. }(BABYLON.ShadowLight));
  48771. BABYLON.DirectionalLight = DirectionalLight;
  48772. })(BABYLON || (BABYLON = {}));
  48773. //# sourceMappingURL=babylon.directionalLight.js.map
  48774. var BABYLON;
  48775. (function (BABYLON) {
  48776. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  48777. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  48778. });
  48779. /**
  48780. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48781. * These values define a cone of light starting from the position, emitting toward the direction.
  48782. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48783. * and the exponent defines the speed of the decay of the light with distance (reach).
  48784. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48785. */
  48786. var SpotLight = /** @class */ (function (_super) {
  48787. __extends(SpotLight, _super);
  48788. /**
  48789. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48790. * It can cast shadows.
  48791. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48792. * @param name The light friendly name
  48793. * @param position The position of the spot light in the scene
  48794. * @param direction The direction of the light in the scene
  48795. * @param angle The cone angle of the light in Radians
  48796. * @param exponent The light decay speed with the distance from the emission spot
  48797. * @param scene The scene the lights belongs to
  48798. */
  48799. function SpotLight(name, position, direction, angle, exponent, scene) {
  48800. var _this = _super.call(this, name, scene) || this;
  48801. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48802. _this._projectionTextureLightNear = 1e-6;
  48803. _this._projectionTextureLightFar = 1000.0;
  48804. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48805. _this._projectionTextureViewLightDirty = true;
  48806. _this._projectionTextureProjectionLightDirty = true;
  48807. _this._projectionTextureDirty = true;
  48808. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48809. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48810. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48811. _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);
  48812. _this.position = position;
  48813. _this.direction = direction;
  48814. _this.angle = angle;
  48815. _this.exponent = exponent;
  48816. return _this;
  48817. }
  48818. Object.defineProperty(SpotLight.prototype, "angle", {
  48819. /**
  48820. * Gets the cone angle of the spot light in Radians.
  48821. */
  48822. get: function () {
  48823. return this._angle;
  48824. },
  48825. /**
  48826. * Sets the cone angle of the spot light in Radians.
  48827. */
  48828. set: function (value) {
  48829. this._angle = value;
  48830. this._projectionTextureProjectionLightDirty = true;
  48831. this.forceProjectionMatrixCompute();
  48832. },
  48833. enumerable: true,
  48834. configurable: true
  48835. });
  48836. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48837. /**
  48838. * Allows scaling the angle of the light for shadow generation only.
  48839. */
  48840. get: function () {
  48841. return this._shadowAngleScale;
  48842. },
  48843. /**
  48844. * Allows scaling the angle of the light for shadow generation only.
  48845. */
  48846. set: function (value) {
  48847. this._shadowAngleScale = value;
  48848. this.forceProjectionMatrixCompute();
  48849. },
  48850. enumerable: true,
  48851. configurable: true
  48852. });
  48853. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48854. /**
  48855. * Allows reading the projecton texture
  48856. */
  48857. get: function () {
  48858. return this._projectionTextureMatrix;
  48859. },
  48860. enumerable: true,
  48861. configurable: true
  48862. });
  48863. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48864. /**
  48865. * Gets the near clip of the Spotlight for texture projection.
  48866. */
  48867. get: function () {
  48868. return this._projectionTextureLightNear;
  48869. },
  48870. /**
  48871. * Sets the near clip of the Spotlight for texture projection.
  48872. */
  48873. set: function (value) {
  48874. this._projectionTextureLightNear = value;
  48875. this._projectionTextureProjectionLightDirty = true;
  48876. },
  48877. enumerable: true,
  48878. configurable: true
  48879. });
  48880. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48881. /**
  48882. * Gets the far clip of the Spotlight for texture projection.
  48883. */
  48884. get: function () {
  48885. return this._projectionTextureLightFar;
  48886. },
  48887. /**
  48888. * Sets the far clip of the Spotlight for texture projection.
  48889. */
  48890. set: function (value) {
  48891. this._projectionTextureLightFar = value;
  48892. this._projectionTextureProjectionLightDirty = true;
  48893. },
  48894. enumerable: true,
  48895. configurable: true
  48896. });
  48897. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48898. /**
  48899. * Gets the Up vector of the Spotlight for texture projection.
  48900. */
  48901. get: function () {
  48902. return this._projectionTextureUpDirection;
  48903. },
  48904. /**
  48905. * Sets the Up vector of the Spotlight for texture projection.
  48906. */
  48907. set: function (value) {
  48908. this._projectionTextureUpDirection = value;
  48909. this._projectionTextureProjectionLightDirty = true;
  48910. },
  48911. enumerable: true,
  48912. configurable: true
  48913. });
  48914. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48915. /**
  48916. * Gets the projection texture of the light.
  48917. */
  48918. get: function () {
  48919. return this._projectionTexture;
  48920. },
  48921. /**
  48922. * Sets the projection texture of the light.
  48923. */
  48924. set: function (value) {
  48925. this._projectionTexture = value;
  48926. this._projectionTextureDirty = true;
  48927. },
  48928. enumerable: true,
  48929. configurable: true
  48930. });
  48931. /**
  48932. * Returns the string "SpotLight".
  48933. * @returns the class name
  48934. */
  48935. SpotLight.prototype.getClassName = function () {
  48936. return "SpotLight";
  48937. };
  48938. /**
  48939. * Returns the integer 2.
  48940. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48941. */
  48942. SpotLight.prototype.getTypeID = function () {
  48943. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  48944. };
  48945. /**
  48946. * Overrides the direction setter to recompute the projection texture view light Matrix.
  48947. */
  48948. SpotLight.prototype._setDirection = function (value) {
  48949. _super.prototype._setDirection.call(this, value);
  48950. this._projectionTextureViewLightDirty = true;
  48951. };
  48952. /**
  48953. * Overrides the position setter to recompute the projection texture view light Matrix.
  48954. */
  48955. SpotLight.prototype._setPosition = function (value) {
  48956. _super.prototype._setPosition.call(this, value);
  48957. this._projectionTextureViewLightDirty = true;
  48958. };
  48959. /**
  48960. * 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.
  48961. * Returns the SpotLight.
  48962. */
  48963. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48964. var activeCamera = this.getScene().activeCamera;
  48965. if (!activeCamera) {
  48966. return;
  48967. }
  48968. this._shadowAngleScale = this._shadowAngleScale || 1;
  48969. var angle = this._shadowAngleScale * this._angle;
  48970. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48971. };
  48972. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  48973. this._projectionTextureViewLightDirty = false;
  48974. this._projectionTextureDirty = true;
  48975. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  48976. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  48977. };
  48978. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  48979. this._projectionTextureProjectionLightDirty = false;
  48980. this._projectionTextureDirty = true;
  48981. var light_far = this.projectionTextureLightFar;
  48982. var light_near = this.projectionTextureLightNear;
  48983. var P = light_far / (light_far - light_near);
  48984. var Q = -P * light_near;
  48985. var S = 1.0 / Math.tan(this._angle / 2.0);
  48986. var A = 1.0;
  48987. 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);
  48988. };
  48989. /**
  48990. * Main function for light texture projection matrix computing.
  48991. */
  48992. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  48993. this._projectionTextureDirty = false;
  48994. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  48995. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  48996. };
  48997. SpotLight.prototype._buildUniformLayout = function () {
  48998. this._uniformBuffer.addUniform("vLightData", 4);
  48999. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49000. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49001. this._uniformBuffer.addUniform("vLightDirection", 3);
  49002. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49003. this._uniformBuffer.addUniform("depthValues", 2);
  49004. this._uniformBuffer.create();
  49005. };
  49006. /**
  49007. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49008. * @param effect The effect to update
  49009. * @param lightIndex The index of the light in the effect to update
  49010. * @returns The spot light
  49011. */
  49012. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49013. var normalizeDirection;
  49014. if (this.computeTransformedInformation()) {
  49015. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49016. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49017. }
  49018. else {
  49019. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49020. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49021. }
  49022. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49023. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49024. if (this._projectionTextureViewLightDirty) {
  49025. this._computeProjectionTextureViewLightMatrix();
  49026. }
  49027. if (this._projectionTextureProjectionLightDirty) {
  49028. this._computeProjectionTextureProjectionLightMatrix();
  49029. }
  49030. if (this._projectionTextureDirty) {
  49031. this._computeProjectionTextureMatrix();
  49032. }
  49033. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49034. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49035. }
  49036. return this;
  49037. };
  49038. /**
  49039. * Disposes the light and the associated resources.
  49040. */
  49041. SpotLight.prototype.dispose = function () {
  49042. _super.prototype.dispose.call(this);
  49043. if (this._projectionTexture) {
  49044. this._projectionTexture.dispose();
  49045. }
  49046. };
  49047. /**
  49048. * Prepares the list of defines specific to the light type.
  49049. * @param defines the list of defines
  49050. * @param lightIndex defines the index of the light for the effect
  49051. */
  49052. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49053. defines["SPOTLIGHT" + lightIndex] = true;
  49054. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49055. };
  49056. __decorate([
  49057. BABYLON.serialize()
  49058. ], SpotLight.prototype, "angle", null);
  49059. __decorate([
  49060. BABYLON.serialize()
  49061. ], SpotLight.prototype, "shadowAngleScale", null);
  49062. __decorate([
  49063. BABYLON.serialize()
  49064. ], SpotLight.prototype, "exponent", void 0);
  49065. __decorate([
  49066. BABYLON.serialize()
  49067. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49068. __decorate([
  49069. BABYLON.serialize()
  49070. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49071. __decorate([
  49072. BABYLON.serialize()
  49073. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49074. __decorate([
  49075. BABYLON.serializeAsTexture("projectedLightTexture")
  49076. ], SpotLight.prototype, "_projectionTexture", void 0);
  49077. return SpotLight;
  49078. }(BABYLON.ShadowLight));
  49079. BABYLON.SpotLight = SpotLight;
  49080. })(BABYLON || (BABYLON = {}));
  49081. //# sourceMappingURL=babylon.spotLight.js.map
  49082. var BABYLON;
  49083. (function (BABYLON) {
  49084. /**
  49085. * Class used to override all child animations of a given target
  49086. */
  49087. var AnimationPropertiesOverride = /** @class */ (function () {
  49088. function AnimationPropertiesOverride() {
  49089. /**
  49090. * Gets or sets a value indicating if animation blending must be used
  49091. */
  49092. this.enableBlending = false;
  49093. /**
  49094. * Gets or sets the blending speed to use when enableBlending is true
  49095. */
  49096. this.blendingSpeed = 0.01;
  49097. /**
  49098. * Gets or sets the default loop mode to use
  49099. */
  49100. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49101. }
  49102. return AnimationPropertiesOverride;
  49103. }());
  49104. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49105. })(BABYLON || (BABYLON = {}));
  49106. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49107. var BABYLON;
  49108. (function (BABYLON) {
  49109. /**
  49110. * Represents the range of an animation
  49111. */
  49112. var AnimationRange = /** @class */ (function () {
  49113. /**
  49114. * Initializes the range of an animation
  49115. * @param name The name of the animation range
  49116. * @param from The starting frame of the animation
  49117. * @param to The ending frame of the animation
  49118. */
  49119. function AnimationRange(
  49120. /**The name of the animation range**/
  49121. name,
  49122. /**The starting frame of the animation */
  49123. from,
  49124. /**The ending frame of the animation*/
  49125. to) {
  49126. this.name = name;
  49127. this.from = from;
  49128. this.to = to;
  49129. }
  49130. /**
  49131. * Makes a copy of the animation range
  49132. * @returns A copy of the animation range
  49133. */
  49134. AnimationRange.prototype.clone = function () {
  49135. return new AnimationRange(this.name, this.from, this.to);
  49136. };
  49137. return AnimationRange;
  49138. }());
  49139. BABYLON.AnimationRange = AnimationRange;
  49140. /**
  49141. * Composed of a frame, and an action function
  49142. */
  49143. var AnimationEvent = /** @class */ (function () {
  49144. /**
  49145. * Initializes the animation event
  49146. * @param frame The frame for which the event is triggered
  49147. * @param action The event to perform when triggered
  49148. * @param onlyOnce Specifies if the event should be triggered only once
  49149. */
  49150. function AnimationEvent(
  49151. /** The frame for which the event is triggered **/
  49152. frame,
  49153. /** The event to perform when triggered **/
  49154. action,
  49155. /** Specifies if the event should be triggered only once**/
  49156. onlyOnce) {
  49157. this.frame = frame;
  49158. this.action = action;
  49159. this.onlyOnce = onlyOnce;
  49160. /**
  49161. * Specifies if the animation event is done
  49162. */
  49163. this.isDone = false;
  49164. }
  49165. /** @hidden */
  49166. AnimationEvent.prototype._clone = function () {
  49167. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49168. };
  49169. return AnimationEvent;
  49170. }());
  49171. BABYLON.AnimationEvent = AnimationEvent;
  49172. /**
  49173. * A cursor which tracks a point on a path
  49174. */
  49175. var PathCursor = /** @class */ (function () {
  49176. /**
  49177. * Initializes the path cursor
  49178. * @param path The path to track
  49179. */
  49180. function PathCursor(path) {
  49181. this.path = path;
  49182. /**
  49183. * Stores path cursor callbacks for when an onchange event is triggered
  49184. */
  49185. this._onchange = new Array();
  49186. /**
  49187. * The value of the path cursor
  49188. */
  49189. this.value = 0;
  49190. /**
  49191. * The animation array of the path cursor
  49192. */
  49193. this.animations = new Array();
  49194. }
  49195. /**
  49196. * Gets the cursor point on the path
  49197. * @returns A point on the path cursor at the cursor location
  49198. */
  49199. PathCursor.prototype.getPoint = function () {
  49200. var point = this.path.getPointAtLengthPosition(this.value);
  49201. return new BABYLON.Vector3(point.x, 0, point.y);
  49202. };
  49203. /**
  49204. * Moves the cursor ahead by the step amount
  49205. * @param step The amount to move the cursor forward
  49206. * @returns This path cursor
  49207. */
  49208. PathCursor.prototype.moveAhead = function (step) {
  49209. if (step === void 0) { step = 0.002; }
  49210. this.move(step);
  49211. return this;
  49212. };
  49213. /**
  49214. * Moves the cursor behind by the step amount
  49215. * @param step The amount to move the cursor back
  49216. * @returns This path cursor
  49217. */
  49218. PathCursor.prototype.moveBack = function (step) {
  49219. if (step === void 0) { step = 0.002; }
  49220. this.move(-step);
  49221. return this;
  49222. };
  49223. /**
  49224. * Moves the cursor by the step amount
  49225. * If the step amount is greater than one, an exception is thrown
  49226. * @param step The amount to move the cursor
  49227. * @returns This path cursor
  49228. */
  49229. PathCursor.prototype.move = function (step) {
  49230. if (Math.abs(step) > 1) {
  49231. throw "step size should be less than 1.";
  49232. }
  49233. this.value += step;
  49234. this.ensureLimits();
  49235. this.raiseOnChange();
  49236. return this;
  49237. };
  49238. /**
  49239. * Ensures that the value is limited between zero and one
  49240. * @returns This path cursor
  49241. */
  49242. PathCursor.prototype.ensureLimits = function () {
  49243. while (this.value > 1) {
  49244. this.value -= 1;
  49245. }
  49246. while (this.value < 0) {
  49247. this.value += 1;
  49248. }
  49249. return this;
  49250. };
  49251. /**
  49252. * Runs onchange callbacks on change (used by the animation engine)
  49253. * @returns This path cursor
  49254. */
  49255. PathCursor.prototype.raiseOnChange = function () {
  49256. var _this = this;
  49257. this._onchange.forEach(function (f) { return f(_this); });
  49258. return this;
  49259. };
  49260. /**
  49261. * Executes a function on change
  49262. * @param f A path cursor onchange callback
  49263. * @returns This path cursor
  49264. */
  49265. PathCursor.prototype.onchange = function (f) {
  49266. this._onchange.push(f);
  49267. return this;
  49268. };
  49269. return PathCursor;
  49270. }());
  49271. BABYLON.PathCursor = PathCursor;
  49272. /**
  49273. * Enum for the animation key frame interpolation type
  49274. */
  49275. var AnimationKeyInterpolation;
  49276. (function (AnimationKeyInterpolation) {
  49277. /**
  49278. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49279. */
  49280. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49281. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49282. /**
  49283. * Class used to store any kind of animation
  49284. */
  49285. var Animation = /** @class */ (function () {
  49286. /**
  49287. * Initializes the animation
  49288. * @param name Name of the animation
  49289. * @param targetProperty Property to animate
  49290. * @param framePerSecond The frames per second of the animation
  49291. * @param dataType The data type of the animation
  49292. * @param loopMode The loop mode of the animation
  49293. * @param enableBlendings Specifies if blending should be enabled
  49294. */
  49295. function Animation(
  49296. /**Name of the animation */
  49297. name,
  49298. /**Property to animate */
  49299. targetProperty,
  49300. /**The frames per second of the animation */
  49301. framePerSecond,
  49302. /**The data type of the animation */
  49303. dataType,
  49304. /**The loop mode of the animation */
  49305. loopMode,
  49306. /**Specifies if blending should be enabled */
  49307. enableBlending) {
  49308. this.name = name;
  49309. this.targetProperty = targetProperty;
  49310. this.framePerSecond = framePerSecond;
  49311. this.dataType = dataType;
  49312. this.loopMode = loopMode;
  49313. this.enableBlending = enableBlending;
  49314. /**
  49315. * @hidden Internal use only
  49316. */
  49317. this._runtimeAnimations = new Array();
  49318. /**
  49319. * The set of event that will be linked to this animation
  49320. */
  49321. this._events = new Array();
  49322. /**
  49323. * Stores the blending speed of the animation
  49324. */
  49325. this.blendingSpeed = 0.01;
  49326. /**
  49327. * Stores the animation ranges for the animation
  49328. */
  49329. this._ranges = {};
  49330. this.targetPropertyPath = targetProperty.split(".");
  49331. this.dataType = dataType;
  49332. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49333. }
  49334. /**
  49335. * @hidden Internal use
  49336. */
  49337. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49338. var dataType = undefined;
  49339. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49340. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49341. }
  49342. else if (from instanceof BABYLON.Quaternion) {
  49343. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49344. }
  49345. else if (from instanceof BABYLON.Vector3) {
  49346. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49347. }
  49348. else if (from instanceof BABYLON.Vector2) {
  49349. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49350. }
  49351. else if (from instanceof BABYLON.Color3) {
  49352. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49353. }
  49354. else if (from instanceof BABYLON.Size) {
  49355. dataType = Animation.ANIMATIONTYPE_SIZE;
  49356. }
  49357. if (dataType == undefined) {
  49358. return null;
  49359. }
  49360. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49361. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49362. animation.setKeys(keys);
  49363. if (easingFunction !== undefined) {
  49364. animation.setEasingFunction(easingFunction);
  49365. }
  49366. return animation;
  49367. };
  49368. /**
  49369. * Sets up an animation
  49370. * @param property The property to animate
  49371. * @param animationType The animation type to apply
  49372. * @param framePerSecond The frames per second of the animation
  49373. * @param easingFunction The easing function used in the animation
  49374. * @returns The created animation
  49375. */
  49376. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49377. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49378. animation.setEasingFunction(easingFunction);
  49379. return animation;
  49380. };
  49381. /**
  49382. * Create and start an animation on a node
  49383. * @param name defines the name of the global animation that will be run on all nodes
  49384. * @param node defines the root node where the animation will take place
  49385. * @param targetProperty defines property to animate
  49386. * @param framePerSecond defines the number of frame per second yo use
  49387. * @param totalFrame defines the number of frames in total
  49388. * @param from defines the initial value
  49389. * @param to defines the final value
  49390. * @param loopMode defines which loop mode you want to use (off by default)
  49391. * @param easingFunction defines the easing function to use (linear by default)
  49392. * @param onAnimationEnd defines the callback to call when animation end
  49393. * @returns the animatable created for this animation
  49394. */
  49395. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49396. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49397. if (!animation) {
  49398. return null;
  49399. }
  49400. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49401. };
  49402. /**
  49403. * Create and start an animation on a node and its descendants
  49404. * @param name defines the name of the global animation that will be run on all nodes
  49405. * @param node defines the root node where the animation will take place
  49406. * @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
  49407. * @param targetProperty defines property to animate
  49408. * @param framePerSecond defines the number of frame per second to use
  49409. * @param totalFrame defines the number of frames in total
  49410. * @param from defines the initial value
  49411. * @param to defines the final value
  49412. * @param loopMode defines which loop mode you want to use (off by default)
  49413. * @param easingFunction defines the easing function to use (linear by default)
  49414. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49415. * @returns the list of animatables created for all nodes
  49416. * @example https://www.babylonjs-playground.com/#MH0VLI
  49417. */
  49418. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49419. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49420. if (!animation) {
  49421. return null;
  49422. }
  49423. var scene = node.getScene();
  49424. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49425. };
  49426. /**
  49427. * Creates a new animation, merges it with the existing animations and starts it
  49428. * @param name Name of the animation
  49429. * @param node Node which contains the scene that begins the animations
  49430. * @param targetProperty Specifies which property to animate
  49431. * @param framePerSecond The frames per second of the animation
  49432. * @param totalFrame The total number of frames
  49433. * @param from The frame at the beginning of the animation
  49434. * @param to The frame at the end of the animation
  49435. * @param loopMode Specifies the loop mode of the animation
  49436. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49437. * @param onAnimationEnd Callback to run once the animation is complete
  49438. * @returns Nullable animation
  49439. */
  49440. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49441. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49442. if (!animation) {
  49443. return null;
  49444. }
  49445. node.animations.push(animation);
  49446. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49447. };
  49448. /**
  49449. * Transition property of an host to the target Value
  49450. * @param property The property to transition
  49451. * @param targetValue The target Value of the property
  49452. * @param host The object where the property to animate belongs
  49453. * @param scene Scene used to run the animation
  49454. * @param frameRate Framerate (in frame/s) to use
  49455. * @param transition The transition type we want to use
  49456. * @param duration The duration of the animation, in milliseconds
  49457. * @param onAnimationEnd Callback trigger at the end of the animation
  49458. * @returns Nullable animation
  49459. */
  49460. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49461. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49462. if (duration <= 0) {
  49463. host[property] = targetValue;
  49464. if (onAnimationEnd) {
  49465. onAnimationEnd();
  49466. }
  49467. return null;
  49468. }
  49469. var endFrame = frameRate * (duration / 1000);
  49470. transition.setKeys([{
  49471. frame: 0,
  49472. value: host[property].clone ? host[property].clone() : host[property]
  49473. },
  49474. {
  49475. frame: endFrame,
  49476. value: targetValue
  49477. }]);
  49478. if (!host.animations) {
  49479. host.animations = [];
  49480. }
  49481. host.animations.push(transition);
  49482. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49483. animation.onAnimationEnd = onAnimationEnd;
  49484. return animation;
  49485. };
  49486. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49487. /**
  49488. * Return the array of runtime animations currently using this animation
  49489. */
  49490. get: function () {
  49491. return this._runtimeAnimations;
  49492. },
  49493. enumerable: true,
  49494. configurable: true
  49495. });
  49496. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49497. /**
  49498. * Specifies if any of the runtime animations are currently running
  49499. */
  49500. get: function () {
  49501. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49502. var runtimeAnimation = _a[_i];
  49503. if (!runtimeAnimation.isStopped) {
  49504. return true;
  49505. }
  49506. }
  49507. return false;
  49508. },
  49509. enumerable: true,
  49510. configurable: true
  49511. });
  49512. // Methods
  49513. /**
  49514. * Converts the animation to a string
  49515. * @param fullDetails support for multiple levels of logging within scene loading
  49516. * @returns String form of the animation
  49517. */
  49518. Animation.prototype.toString = function (fullDetails) {
  49519. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49520. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49521. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49522. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49523. if (fullDetails) {
  49524. ret += ", Ranges: {";
  49525. var first = true;
  49526. for (var name in this._ranges) {
  49527. if (first) {
  49528. ret += ", ";
  49529. first = false;
  49530. }
  49531. ret += name;
  49532. }
  49533. ret += "}";
  49534. }
  49535. return ret;
  49536. };
  49537. /**
  49538. * Add an event to this animation
  49539. * @param event Event to add
  49540. */
  49541. Animation.prototype.addEvent = function (event) {
  49542. this._events.push(event);
  49543. };
  49544. /**
  49545. * Remove all events found at the given frame
  49546. * @param frame The frame to remove events from
  49547. */
  49548. Animation.prototype.removeEvents = function (frame) {
  49549. for (var index = 0; index < this._events.length; index++) {
  49550. if (this._events[index].frame === frame) {
  49551. this._events.splice(index, 1);
  49552. index--;
  49553. }
  49554. }
  49555. };
  49556. /**
  49557. * Retrieves all the events from the animation
  49558. * @returns Events from the animation
  49559. */
  49560. Animation.prototype.getEvents = function () {
  49561. return this._events;
  49562. };
  49563. /**
  49564. * Creates an animation range
  49565. * @param name Name of the animation range
  49566. * @param from Starting frame of the animation range
  49567. * @param to Ending frame of the animation
  49568. */
  49569. Animation.prototype.createRange = function (name, from, to) {
  49570. // check name not already in use; could happen for bones after serialized
  49571. if (!this._ranges[name]) {
  49572. this._ranges[name] = new AnimationRange(name, from, to);
  49573. }
  49574. };
  49575. /**
  49576. * Deletes an animation range by name
  49577. * @param name Name of the animation range to delete
  49578. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49579. */
  49580. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49581. if (deleteFrames === void 0) { deleteFrames = true; }
  49582. var range = this._ranges[name];
  49583. if (!range) {
  49584. return;
  49585. }
  49586. if (deleteFrames) {
  49587. var from = range.from;
  49588. var to = range.to;
  49589. // this loop MUST go high to low for multiple splices to work
  49590. for (var key = this._keys.length - 1; key >= 0; key--) {
  49591. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49592. this._keys.splice(key, 1);
  49593. }
  49594. }
  49595. }
  49596. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49597. };
  49598. /**
  49599. * Gets the animation range by name, or null if not defined
  49600. * @param name Name of the animation range
  49601. * @returns Nullable animation range
  49602. */
  49603. Animation.prototype.getRange = function (name) {
  49604. return this._ranges[name];
  49605. };
  49606. /**
  49607. * Gets the key frames from the animation
  49608. * @returns The key frames of the animation
  49609. */
  49610. Animation.prototype.getKeys = function () {
  49611. return this._keys;
  49612. };
  49613. /**
  49614. * Gets the highest frame rate of the animation
  49615. * @returns Highest frame rate of the animation
  49616. */
  49617. Animation.prototype.getHighestFrame = function () {
  49618. var ret = 0;
  49619. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49620. if (ret < this._keys[key].frame) {
  49621. ret = this._keys[key].frame;
  49622. }
  49623. }
  49624. return ret;
  49625. };
  49626. /**
  49627. * Gets the easing function of the animation
  49628. * @returns Easing function of the animation
  49629. */
  49630. Animation.prototype.getEasingFunction = function () {
  49631. return this._easingFunction;
  49632. };
  49633. /**
  49634. * Sets the easing function of the animation
  49635. * @param easingFunction A custom mathematical formula for animation
  49636. */
  49637. Animation.prototype.setEasingFunction = function (easingFunction) {
  49638. this._easingFunction = easingFunction;
  49639. };
  49640. /**
  49641. * Interpolates a scalar linearly
  49642. * @param startValue Start value of the animation curve
  49643. * @param endValue End value of the animation curve
  49644. * @param gradient Scalar amount to interpolate
  49645. * @returns Interpolated scalar value
  49646. */
  49647. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49648. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49649. };
  49650. /**
  49651. * Interpolates a scalar cubically
  49652. * @param startValue Start value of the animation curve
  49653. * @param outTangent End tangent of the animation
  49654. * @param endValue End value of the animation curve
  49655. * @param inTangent Start tangent of the animation curve
  49656. * @param gradient Scalar amount to interpolate
  49657. * @returns Interpolated scalar value
  49658. */
  49659. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49660. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49661. };
  49662. /**
  49663. * Interpolates a quaternion using a spherical linear interpolation
  49664. * @param startValue Start value of the animation curve
  49665. * @param endValue End value of the animation curve
  49666. * @param gradient Scalar amount to interpolate
  49667. * @returns Interpolated quaternion value
  49668. */
  49669. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49670. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49671. };
  49672. /**
  49673. * Interpolates a quaternion cubically
  49674. * @param startValue Start value of the animation curve
  49675. * @param outTangent End tangent of the animation curve
  49676. * @param endValue End value of the animation curve
  49677. * @param inTangent Start tangent of the animation curve
  49678. * @param gradient Scalar amount to interpolate
  49679. * @returns Interpolated quaternion value
  49680. */
  49681. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49682. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49683. };
  49684. /**
  49685. * Interpolates a Vector3 linearl
  49686. * @param startValue Start value of the animation curve
  49687. * @param endValue End value of the animation curve
  49688. * @param gradient Scalar amount to interpolate
  49689. * @returns Interpolated scalar value
  49690. */
  49691. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49692. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49693. };
  49694. /**
  49695. * Interpolates a Vector3 cubically
  49696. * @param startValue Start value of the animation curve
  49697. * @param outTangent End tangent of the animation
  49698. * @param endValue End value of the animation curve
  49699. * @param inTangent Start tangent of the animation curve
  49700. * @param gradient Scalar amount to interpolate
  49701. * @returns InterpolatedVector3 value
  49702. */
  49703. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49704. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49705. };
  49706. /**
  49707. * Interpolates a Vector2 linearly
  49708. * @param startValue Start value of the animation curve
  49709. * @param endValue End value of the animation curve
  49710. * @param gradient Scalar amount to interpolate
  49711. * @returns Interpolated Vector2 value
  49712. */
  49713. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49714. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49715. };
  49716. /**
  49717. * Interpolates a Vector2 cubically
  49718. * @param startValue Start value of the animation curve
  49719. * @param outTangent End tangent of the animation
  49720. * @param endValue End value of the animation curve
  49721. * @param inTangent Start tangent of the animation curve
  49722. * @param gradient Scalar amount to interpolate
  49723. * @returns Interpolated Vector2 value
  49724. */
  49725. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49726. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49727. };
  49728. /**
  49729. * Interpolates a size linearly
  49730. * @param startValue Start value of the animation curve
  49731. * @param endValue End value of the animation curve
  49732. * @param gradient Scalar amount to interpolate
  49733. * @returns Interpolated Size value
  49734. */
  49735. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49736. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49737. };
  49738. /**
  49739. * Interpolates a Color3 linearly
  49740. * @param startValue Start value of the animation curve
  49741. * @param endValue End value of the animation curve
  49742. * @param gradient Scalar amount to interpolate
  49743. * @returns Interpolated Color3 value
  49744. */
  49745. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49746. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49747. };
  49748. /**
  49749. * @hidden Internal use only
  49750. */
  49751. Animation.prototype._getKeyValue = function (value) {
  49752. if (typeof value === "function") {
  49753. return value();
  49754. }
  49755. return value;
  49756. };
  49757. /**
  49758. * @hidden Internal use only
  49759. */
  49760. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49761. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49762. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49763. }
  49764. var keys = this.getKeys();
  49765. // Try to get a hash to find the right key
  49766. 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));
  49767. if (keys[startKeyIndex].frame >= currentFrame) {
  49768. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49769. startKeyIndex--;
  49770. }
  49771. }
  49772. for (var key = startKeyIndex; key < keys.length; key++) {
  49773. var endKey = keys[key + 1];
  49774. if (endKey.frame >= currentFrame) {
  49775. var startKey = keys[key];
  49776. var startValue = this._getKeyValue(startKey.value);
  49777. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49778. return startValue;
  49779. }
  49780. var endValue = this._getKeyValue(endKey.value);
  49781. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49782. var frameDelta = endKey.frame - startKey.frame;
  49783. // gradient : percent of currentFrame between the frame inf and the frame sup
  49784. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49785. // check for easingFunction and correction of gradient
  49786. var easingFunction = this.getEasingFunction();
  49787. if (easingFunction != null) {
  49788. gradient = easingFunction.ease(gradient);
  49789. }
  49790. switch (this.dataType) {
  49791. // Float
  49792. case Animation.ANIMATIONTYPE_FLOAT:
  49793. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49794. switch (loopMode) {
  49795. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49796. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49797. return floatValue;
  49798. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49799. return offsetValue * repeatCount + floatValue;
  49800. }
  49801. break;
  49802. // Quaternion
  49803. case Animation.ANIMATIONTYPE_QUATERNION:
  49804. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49805. switch (loopMode) {
  49806. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49807. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49808. return quatValue;
  49809. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49810. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49811. }
  49812. return quatValue;
  49813. // Vector3
  49814. case Animation.ANIMATIONTYPE_VECTOR3:
  49815. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49816. switch (loopMode) {
  49817. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49818. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49819. return vec3Value;
  49820. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49821. return vec3Value.add(offsetValue.scale(repeatCount));
  49822. }
  49823. // Vector2
  49824. case Animation.ANIMATIONTYPE_VECTOR2:
  49825. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49826. switch (loopMode) {
  49827. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49828. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49829. return vec2Value;
  49830. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49831. return vec2Value.add(offsetValue.scale(repeatCount));
  49832. }
  49833. // Size
  49834. case Animation.ANIMATIONTYPE_SIZE:
  49835. switch (loopMode) {
  49836. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49837. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49838. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49839. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49840. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49841. }
  49842. // Color3
  49843. case Animation.ANIMATIONTYPE_COLOR3:
  49844. switch (loopMode) {
  49845. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49846. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49847. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49848. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49849. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49850. }
  49851. // Matrix
  49852. case Animation.ANIMATIONTYPE_MATRIX:
  49853. switch (loopMode) {
  49854. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49855. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49856. if (Animation.AllowMatricesInterpolation) {
  49857. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49858. }
  49859. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49860. return startValue;
  49861. }
  49862. default:
  49863. break;
  49864. }
  49865. break;
  49866. }
  49867. }
  49868. return this._getKeyValue(keys[keys.length - 1].value);
  49869. };
  49870. /**
  49871. * Defines the function to use to interpolate matrices
  49872. * @param startValue defines the start matrix
  49873. * @param endValue defines the end matrix
  49874. * @param gradient defines the gradient between both matrices
  49875. * @param result defines an optional target matrix where to store the interpolation
  49876. * @returns the interpolated matrix
  49877. */
  49878. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49879. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49880. if (result) {
  49881. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49882. return result;
  49883. }
  49884. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49885. }
  49886. if (result) {
  49887. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49888. return result;
  49889. }
  49890. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49891. };
  49892. /**
  49893. * Makes a copy of the animation
  49894. * @returns Cloned animation
  49895. */
  49896. Animation.prototype.clone = function () {
  49897. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49898. clone.enableBlending = this.enableBlending;
  49899. clone.blendingSpeed = this.blendingSpeed;
  49900. if (this._keys) {
  49901. clone.setKeys(this._keys);
  49902. }
  49903. if (this._ranges) {
  49904. clone._ranges = {};
  49905. for (var name in this._ranges) {
  49906. var range = this._ranges[name];
  49907. if (!range) {
  49908. continue;
  49909. }
  49910. clone._ranges[name] = range.clone();
  49911. }
  49912. }
  49913. return clone;
  49914. };
  49915. /**
  49916. * Sets the key frames of the animation
  49917. * @param values The animation key frames to set
  49918. */
  49919. Animation.prototype.setKeys = function (values) {
  49920. this._keys = values.slice(0);
  49921. };
  49922. /**
  49923. * Serializes the animation to an object
  49924. * @returns Serialized object
  49925. */
  49926. Animation.prototype.serialize = function () {
  49927. var serializationObject = {};
  49928. serializationObject.name = this.name;
  49929. serializationObject.property = this.targetProperty;
  49930. serializationObject.framePerSecond = this.framePerSecond;
  49931. serializationObject.dataType = this.dataType;
  49932. serializationObject.loopBehavior = this.loopMode;
  49933. serializationObject.enableBlending = this.enableBlending;
  49934. serializationObject.blendingSpeed = this.blendingSpeed;
  49935. var dataType = this.dataType;
  49936. serializationObject.keys = [];
  49937. var keys = this.getKeys();
  49938. for (var index = 0; index < keys.length; index++) {
  49939. var animationKey = keys[index];
  49940. var key = {};
  49941. key.frame = animationKey.frame;
  49942. switch (dataType) {
  49943. case Animation.ANIMATIONTYPE_FLOAT:
  49944. key.values = [animationKey.value];
  49945. break;
  49946. case Animation.ANIMATIONTYPE_QUATERNION:
  49947. case Animation.ANIMATIONTYPE_MATRIX:
  49948. case Animation.ANIMATIONTYPE_VECTOR3:
  49949. case Animation.ANIMATIONTYPE_COLOR3:
  49950. key.values = animationKey.value.asArray();
  49951. break;
  49952. }
  49953. serializationObject.keys.push(key);
  49954. }
  49955. serializationObject.ranges = [];
  49956. for (var name in this._ranges) {
  49957. var source = this._ranges[name];
  49958. if (!source) {
  49959. continue;
  49960. }
  49961. var range = {};
  49962. range.name = name;
  49963. range.from = source.from;
  49964. range.to = source.to;
  49965. serializationObject.ranges.push(range);
  49966. }
  49967. return serializationObject;
  49968. };
  49969. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49970. /**
  49971. * Get the float animation type
  49972. */
  49973. get: function () {
  49974. return Animation._ANIMATIONTYPE_FLOAT;
  49975. },
  49976. enumerable: true,
  49977. configurable: true
  49978. });
  49979. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49980. /**
  49981. * Get the Vector3 animation type
  49982. */
  49983. get: function () {
  49984. return Animation._ANIMATIONTYPE_VECTOR3;
  49985. },
  49986. enumerable: true,
  49987. configurable: true
  49988. });
  49989. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49990. /**
  49991. * Get the Vectpr2 animation type
  49992. */
  49993. get: function () {
  49994. return Animation._ANIMATIONTYPE_VECTOR2;
  49995. },
  49996. enumerable: true,
  49997. configurable: true
  49998. });
  49999. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50000. /**
  50001. * Get the Size animation type
  50002. */
  50003. get: function () {
  50004. return Animation._ANIMATIONTYPE_SIZE;
  50005. },
  50006. enumerable: true,
  50007. configurable: true
  50008. });
  50009. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50010. /**
  50011. * Get the Quaternion animation type
  50012. */
  50013. get: function () {
  50014. return Animation._ANIMATIONTYPE_QUATERNION;
  50015. },
  50016. enumerable: true,
  50017. configurable: true
  50018. });
  50019. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50020. /**
  50021. * Get the Matrix animation type
  50022. */
  50023. get: function () {
  50024. return Animation._ANIMATIONTYPE_MATRIX;
  50025. },
  50026. enumerable: true,
  50027. configurable: true
  50028. });
  50029. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50030. /**
  50031. * Get the Color3 animation type
  50032. */
  50033. get: function () {
  50034. return Animation._ANIMATIONTYPE_COLOR3;
  50035. },
  50036. enumerable: true,
  50037. configurable: true
  50038. });
  50039. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50040. /**
  50041. * Get the Relative Loop Mode
  50042. */
  50043. get: function () {
  50044. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50045. },
  50046. enumerable: true,
  50047. configurable: true
  50048. });
  50049. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50050. /**
  50051. * Get the Cycle Loop Mode
  50052. */
  50053. get: function () {
  50054. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50055. },
  50056. enumerable: true,
  50057. configurable: true
  50058. });
  50059. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50060. /**
  50061. * Get the Constant Loop Mode
  50062. */
  50063. get: function () {
  50064. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50065. },
  50066. enumerable: true,
  50067. configurable: true
  50068. });
  50069. /** @hidden */
  50070. Animation._UniversalLerp = function (left, right, amount) {
  50071. var constructor = left.constructor;
  50072. if (constructor.Lerp) { // Lerp supported
  50073. return constructor.Lerp(left, right, amount);
  50074. }
  50075. else if (constructor.Slerp) { // Slerp supported
  50076. return constructor.Slerp(left, right, amount);
  50077. }
  50078. else if (left.toFixed) { // Number
  50079. return left * (1.0 - amount) + amount * right;
  50080. }
  50081. else { // Blending not supported
  50082. return right;
  50083. }
  50084. };
  50085. /**
  50086. * Parses an animation object and creates an animation
  50087. * @param parsedAnimation Parsed animation object
  50088. * @returns Animation object
  50089. */
  50090. Animation.Parse = function (parsedAnimation) {
  50091. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50092. var dataType = parsedAnimation.dataType;
  50093. var keys = [];
  50094. var data;
  50095. var index;
  50096. if (parsedAnimation.enableBlending) {
  50097. animation.enableBlending = parsedAnimation.enableBlending;
  50098. }
  50099. if (parsedAnimation.blendingSpeed) {
  50100. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50101. }
  50102. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50103. var key = parsedAnimation.keys[index];
  50104. var inTangent;
  50105. var outTangent;
  50106. switch (dataType) {
  50107. case Animation.ANIMATIONTYPE_FLOAT:
  50108. data = key.values[0];
  50109. if (key.values.length >= 1) {
  50110. inTangent = key.values[1];
  50111. }
  50112. if (key.values.length >= 2) {
  50113. outTangent = key.values[2];
  50114. }
  50115. break;
  50116. case Animation.ANIMATIONTYPE_QUATERNION:
  50117. data = BABYLON.Quaternion.FromArray(key.values);
  50118. if (key.values.length >= 8) {
  50119. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50120. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50121. inTangent = _inTangent;
  50122. }
  50123. }
  50124. if (key.values.length >= 12) {
  50125. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50126. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50127. outTangent = _outTangent;
  50128. }
  50129. }
  50130. break;
  50131. case Animation.ANIMATIONTYPE_MATRIX:
  50132. data = BABYLON.Matrix.FromArray(key.values);
  50133. break;
  50134. case Animation.ANIMATIONTYPE_COLOR3:
  50135. data = BABYLON.Color3.FromArray(key.values);
  50136. break;
  50137. case Animation.ANIMATIONTYPE_VECTOR3:
  50138. default:
  50139. data = BABYLON.Vector3.FromArray(key.values);
  50140. break;
  50141. }
  50142. var keyData = {};
  50143. keyData.frame = key.frame;
  50144. keyData.value = data;
  50145. if (inTangent != undefined) {
  50146. keyData.inTangent = inTangent;
  50147. }
  50148. if (outTangent != undefined) {
  50149. keyData.outTangent = outTangent;
  50150. }
  50151. keys.push(keyData);
  50152. }
  50153. animation.setKeys(keys);
  50154. if (parsedAnimation.ranges) {
  50155. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50156. data = parsedAnimation.ranges[index];
  50157. animation.createRange(data.name, data.from, data.to);
  50158. }
  50159. }
  50160. return animation;
  50161. };
  50162. /**
  50163. * Appends the serialized animations from the source animations
  50164. * @param source Source containing the animations
  50165. * @param destination Target to store the animations
  50166. */
  50167. Animation.AppendSerializedAnimations = function (source, destination) {
  50168. if (source.animations) {
  50169. destination.animations = [];
  50170. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50171. var animation = source.animations[animationIndex];
  50172. destination.animations.push(animation.serialize());
  50173. }
  50174. }
  50175. };
  50176. /**
  50177. * Use matrix interpolation instead of using direct key value when animating matrices
  50178. */
  50179. Animation.AllowMatricesInterpolation = false;
  50180. /**
  50181. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50182. */
  50183. Animation.AllowMatrixDecomposeForInterpolation = true;
  50184. // Statics
  50185. /**
  50186. * Float animation type
  50187. */
  50188. Animation._ANIMATIONTYPE_FLOAT = 0;
  50189. /**
  50190. * Vector3 animation type
  50191. */
  50192. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50193. /**
  50194. * Quaternion animation type
  50195. */
  50196. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50197. /**
  50198. * Matrix animation type
  50199. */
  50200. Animation._ANIMATIONTYPE_MATRIX = 3;
  50201. /**
  50202. * Color3 animation type
  50203. */
  50204. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50205. /**
  50206. * Vector2 animation type
  50207. */
  50208. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50209. /**
  50210. * Size animation type
  50211. */
  50212. Animation._ANIMATIONTYPE_SIZE = 6;
  50213. /**
  50214. * Relative Loop Mode
  50215. */
  50216. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50217. /**
  50218. * Cycle Loop Mode
  50219. */
  50220. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50221. /**
  50222. * Constant Loop Mode
  50223. */
  50224. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50225. return Animation;
  50226. }());
  50227. BABYLON.Animation = Animation;
  50228. })(BABYLON || (BABYLON = {}));
  50229. //# sourceMappingURL=babylon.animation.js.map
  50230. var BABYLON;
  50231. (function (BABYLON) {
  50232. /**
  50233. * This class defines the direct association between an animation and a target
  50234. */
  50235. var TargetedAnimation = /** @class */ (function () {
  50236. function TargetedAnimation() {
  50237. }
  50238. return TargetedAnimation;
  50239. }());
  50240. BABYLON.TargetedAnimation = TargetedAnimation;
  50241. /**
  50242. * Use this class to create coordinated animations on multiple targets
  50243. */
  50244. var AnimationGroup = /** @class */ (function () {
  50245. function AnimationGroup(name, scene) {
  50246. if (scene === void 0) { scene = null; }
  50247. this.name = name;
  50248. this._targetedAnimations = new Array();
  50249. this._animatables = new Array();
  50250. this._from = Number.MAX_VALUE;
  50251. this._to = -Number.MAX_VALUE;
  50252. this._speedRatio = 1;
  50253. this.onAnimationEndObservable = new BABYLON.Observable();
  50254. /**
  50255. * This observable will notify when all animations have ended.
  50256. */
  50257. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50258. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50259. this._scene.animationGroups.push(this);
  50260. }
  50261. Object.defineProperty(AnimationGroup.prototype, "from", {
  50262. /**
  50263. * Gets the first frame
  50264. */
  50265. get: function () {
  50266. return this._from;
  50267. },
  50268. enumerable: true,
  50269. configurable: true
  50270. });
  50271. Object.defineProperty(AnimationGroup.prototype, "to", {
  50272. /**
  50273. * Gets the last frame
  50274. */
  50275. get: function () {
  50276. return this._to;
  50277. },
  50278. enumerable: true,
  50279. configurable: true
  50280. });
  50281. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50282. /**
  50283. * Define if the animations are started
  50284. */
  50285. get: function () {
  50286. return this._isStarted;
  50287. },
  50288. enumerable: true,
  50289. configurable: true
  50290. });
  50291. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50292. /**
  50293. * Gets or sets the speed ratio to use for all animations
  50294. */
  50295. get: function () {
  50296. return this._speedRatio;
  50297. },
  50298. /**
  50299. * Gets or sets the speed ratio to use for all animations
  50300. */
  50301. set: function (value) {
  50302. if (this._speedRatio === value) {
  50303. return;
  50304. }
  50305. this._speedRatio = value;
  50306. for (var index = 0; index < this._animatables.length; index++) {
  50307. var animatable = this._animatables[index];
  50308. animatable.speedRatio = this._speedRatio;
  50309. }
  50310. },
  50311. enumerable: true,
  50312. configurable: true
  50313. });
  50314. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50315. /**
  50316. * Gets the targeted animations for this animation group
  50317. */
  50318. get: function () {
  50319. return this._targetedAnimations;
  50320. },
  50321. enumerable: true,
  50322. configurable: true
  50323. });
  50324. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50325. /**
  50326. * returning the list of animatables controlled by this animation group.
  50327. */
  50328. get: function () {
  50329. return this._animatables;
  50330. },
  50331. enumerable: true,
  50332. configurable: true
  50333. });
  50334. /**
  50335. * Add an animation (with its target) in the group
  50336. * @param animation defines the animation we want to add
  50337. * @param target defines the target of the animation
  50338. * @returns the {BABYLON.TargetedAnimation} object
  50339. */
  50340. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50341. var targetedAnimation = {
  50342. animation: animation,
  50343. target: target
  50344. };
  50345. var keys = animation.getKeys();
  50346. if (this._from > keys[0].frame) {
  50347. this._from = keys[0].frame;
  50348. }
  50349. if (this._to < keys[keys.length - 1].frame) {
  50350. this._to = keys[keys.length - 1].frame;
  50351. }
  50352. this._targetedAnimations.push(targetedAnimation);
  50353. return targetedAnimation;
  50354. };
  50355. /**
  50356. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50357. * It can add constant keys at begin or end
  50358. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50359. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50360. */
  50361. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50362. if (beginFrame === void 0) { beginFrame = null; }
  50363. if (endFrame === void 0) { endFrame = null; }
  50364. if (beginFrame == null)
  50365. beginFrame = this._from;
  50366. if (endFrame == null)
  50367. endFrame = this._to;
  50368. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50369. var targetedAnimation = this._targetedAnimations[index];
  50370. var keys = targetedAnimation.animation.getKeys();
  50371. var startKey = keys[0];
  50372. var endKey = keys[keys.length - 1];
  50373. if (startKey.frame > beginFrame) {
  50374. var newKey = {
  50375. frame: beginFrame,
  50376. value: startKey.value,
  50377. inTangent: startKey.inTangent,
  50378. outTangent: startKey.outTangent,
  50379. interpolation: startKey.interpolation
  50380. };
  50381. keys.splice(0, 0, newKey);
  50382. }
  50383. if (endKey.frame < endFrame) {
  50384. var newKey = {
  50385. frame: endFrame,
  50386. value: endKey.value,
  50387. inTangent: endKey.outTangent,
  50388. outTangent: endKey.outTangent,
  50389. interpolation: endKey.interpolation
  50390. };
  50391. keys.push(newKey);
  50392. }
  50393. }
  50394. this._from = beginFrame;
  50395. this._to = endFrame;
  50396. return this;
  50397. };
  50398. /**
  50399. * Start all animations on given targets
  50400. * @param loop defines if animations must loop
  50401. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50402. * @param from defines the from key (optional)
  50403. * @param to defines the to key (optional)
  50404. * @returns the current animation group
  50405. */
  50406. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50407. var _this = this;
  50408. if (loop === void 0) { loop = false; }
  50409. if (speedRatio === void 0) { speedRatio = 1; }
  50410. if (this._isStarted || this._targetedAnimations.length === 0) {
  50411. return this;
  50412. }
  50413. var _loop_1 = function (targetedAnimation) {
  50414. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50415. animatable.onAnimationEnd = function () {
  50416. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50417. _this._checkAnimationGroupEnded(animatable);
  50418. };
  50419. this_1._animatables.push(animatable);
  50420. };
  50421. var this_1 = this;
  50422. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50423. var targetedAnimation = _a[_i];
  50424. _loop_1(targetedAnimation);
  50425. }
  50426. this._speedRatio = speedRatio;
  50427. this._isStarted = true;
  50428. return this;
  50429. };
  50430. /**
  50431. * Pause all animations
  50432. */
  50433. AnimationGroup.prototype.pause = function () {
  50434. if (!this._isStarted) {
  50435. return this;
  50436. }
  50437. for (var index = 0; index < this._animatables.length; index++) {
  50438. var animatable = this._animatables[index];
  50439. animatable.pause();
  50440. }
  50441. return this;
  50442. };
  50443. /**
  50444. * Play all animations to initial state
  50445. * This function will start() the animations if they were not started or will restart() them if they were paused
  50446. * @param loop defines if animations must loop
  50447. */
  50448. AnimationGroup.prototype.play = function (loop) {
  50449. // only if all animatables are ready and exist
  50450. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50451. if (loop !== undefined) {
  50452. for (var index = 0; index < this._animatables.length; index++) {
  50453. var animatable = this._animatables[index];
  50454. animatable.loopAnimation = loop;
  50455. }
  50456. }
  50457. this.restart();
  50458. }
  50459. else {
  50460. this.stop();
  50461. this.start(loop, this._speedRatio);
  50462. }
  50463. return this;
  50464. };
  50465. /**
  50466. * Reset all animations to initial state
  50467. */
  50468. AnimationGroup.prototype.reset = function () {
  50469. if (!this._isStarted) {
  50470. return this;
  50471. }
  50472. for (var index = 0; index < this._animatables.length; index++) {
  50473. var animatable = this._animatables[index];
  50474. animatable.reset();
  50475. }
  50476. return this;
  50477. };
  50478. /**
  50479. * Restart animations from key 0
  50480. */
  50481. AnimationGroup.prototype.restart = function () {
  50482. if (!this._isStarted) {
  50483. return this;
  50484. }
  50485. for (var index = 0; index < this._animatables.length; index++) {
  50486. var animatable = this._animatables[index];
  50487. animatable.restart();
  50488. }
  50489. return this;
  50490. };
  50491. /**
  50492. * Stop all animations
  50493. */
  50494. AnimationGroup.prototype.stop = function () {
  50495. if (!this._isStarted) {
  50496. return this;
  50497. }
  50498. var list = this._animatables.slice();
  50499. for (var index = 0; index < list.length; index++) {
  50500. list[index].stop();
  50501. }
  50502. this._isStarted = false;
  50503. return this;
  50504. };
  50505. /**
  50506. * Set animation weight for all animatables
  50507. * @param weight defines the weight to use
  50508. * @return the animationGroup
  50509. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50510. */
  50511. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50512. for (var index = 0; index < this._animatables.length; index++) {
  50513. var animatable = this._animatables[index];
  50514. animatable.weight = weight;
  50515. }
  50516. return this;
  50517. };
  50518. /**
  50519. * Synchronize and normalize all animatables with a source animatable
  50520. * @param root defines the root animatable to synchronize with
  50521. * @return the animationGroup
  50522. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50523. */
  50524. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50525. for (var index = 0; index < this._animatables.length; index++) {
  50526. var animatable = this._animatables[index];
  50527. animatable.syncWith(root);
  50528. }
  50529. return this;
  50530. };
  50531. /**
  50532. * Goes to a specific frame in this animation group
  50533. * @param frame the frame number to go to
  50534. * @return the animationGroup
  50535. */
  50536. AnimationGroup.prototype.goToFrame = function (frame) {
  50537. if (!this._isStarted) {
  50538. return this;
  50539. }
  50540. for (var index = 0; index < this._animatables.length; index++) {
  50541. var animatable = this._animatables[index];
  50542. animatable.goToFrame(frame);
  50543. }
  50544. return this;
  50545. };
  50546. /**
  50547. * Dispose all associated resources
  50548. */
  50549. AnimationGroup.prototype.dispose = function () {
  50550. this._targetedAnimations = [];
  50551. this._animatables = [];
  50552. var index = this._scene.animationGroups.indexOf(this);
  50553. if (index > -1) {
  50554. this._scene.animationGroups.splice(index, 1);
  50555. }
  50556. };
  50557. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50558. // animatable should be taken out of the array
  50559. var idx = this._animatables.indexOf(animatable);
  50560. if (idx > -1) {
  50561. this._animatables.splice(idx, 1);
  50562. }
  50563. // all animatables were removed? animation group ended!
  50564. if (this._animatables.length === 0) {
  50565. this._isStarted = false;
  50566. this.onAnimationGroupEndObservable.notifyObservers(this);
  50567. }
  50568. };
  50569. return AnimationGroup;
  50570. }());
  50571. BABYLON.AnimationGroup = AnimationGroup;
  50572. })(BABYLON || (BABYLON = {}));
  50573. //# sourceMappingURL=babylon.animationGroup.js.map
  50574. var BABYLON;
  50575. (function (BABYLON) {
  50576. /**
  50577. * Defines a runtime animation
  50578. */
  50579. var RuntimeAnimation = /** @class */ (function () {
  50580. /**
  50581. * Create a new RuntimeAnimation object
  50582. * @param target defines the target of the animation
  50583. * @param animation defines the source animation object
  50584. * @param scene defines the hosting scene
  50585. * @param host defines the initiating Animatable
  50586. */
  50587. function RuntimeAnimation(target, animation, scene, host) {
  50588. var _this = this;
  50589. this._events = new Array();
  50590. /**
  50591. * The current frame of the runtime animation
  50592. */
  50593. this._currentFrame = 0;
  50594. /**
  50595. * The original value of the runtime animation
  50596. */
  50597. this._originalValue = new Array();
  50598. /**
  50599. * The offsets cache of the runtime animation
  50600. */
  50601. this._offsetsCache = {};
  50602. /**
  50603. * The high limits cache of the runtime animation
  50604. */
  50605. this._highLimitsCache = {};
  50606. /**
  50607. * Specifies if the runtime animation has been stopped
  50608. */
  50609. this._stopped = false;
  50610. /**
  50611. * The blending factor of the runtime animation
  50612. */
  50613. this._blendingFactor = 0;
  50614. /**
  50615. * The target path of the runtime animation
  50616. */
  50617. this._targetPath = "";
  50618. /**
  50619. * The weight of the runtime animation
  50620. */
  50621. this._weight = 1.0;
  50622. /**
  50623. * The ratio offset of the runtime animation
  50624. */
  50625. this._ratioOffset = 0;
  50626. /**
  50627. * The previous delay of the runtime animation
  50628. */
  50629. this._previousDelay = 0;
  50630. /**
  50631. * The previous ratio of the runtime animation
  50632. */
  50633. this._previousRatio = 0;
  50634. this._animation = animation;
  50635. this._target = target;
  50636. this._scene = scene;
  50637. this._host = host;
  50638. animation._runtimeAnimations.push(this);
  50639. // Cloning events locally
  50640. var events = animation.getEvents();
  50641. if (events && events.length > 0) {
  50642. events.forEach(function (e) {
  50643. _this._events.push(e._clone());
  50644. });
  50645. }
  50646. }
  50647. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50648. /**
  50649. * Gets the current frame of the runtime animation
  50650. */
  50651. get: function () {
  50652. return this._currentFrame;
  50653. },
  50654. enumerable: true,
  50655. configurable: true
  50656. });
  50657. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50658. /**
  50659. * Gets the weight of the runtime animation
  50660. */
  50661. get: function () {
  50662. return this._weight;
  50663. },
  50664. enumerable: true,
  50665. configurable: true
  50666. });
  50667. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50668. /**
  50669. * Gets the current value of the runtime animation
  50670. */
  50671. get: function () {
  50672. return this._currentValue;
  50673. },
  50674. enumerable: true,
  50675. configurable: true
  50676. });
  50677. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50678. /**
  50679. * Gets the target path of the runtime animation
  50680. */
  50681. get: function () {
  50682. return this._targetPath;
  50683. },
  50684. enumerable: true,
  50685. configurable: true
  50686. });
  50687. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50688. /**
  50689. * Gets the actual target of the runtime animation
  50690. */
  50691. get: function () {
  50692. return this._activeTarget;
  50693. },
  50694. enumerable: true,
  50695. configurable: true
  50696. });
  50697. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50698. /**
  50699. * Gets the animation from the runtime animation
  50700. */
  50701. get: function () {
  50702. return this._animation;
  50703. },
  50704. enumerable: true,
  50705. configurable: true
  50706. });
  50707. /**
  50708. * Resets the runtime animation to the beginning
  50709. * @param restoreOriginal defines whether to restore the target property to the original value
  50710. */
  50711. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50712. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50713. if (restoreOriginal) {
  50714. if (this._target instanceof Array) {
  50715. var index = 0;
  50716. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50717. var target = _a[_i];
  50718. if (this._originalValue[index] !== undefined) {
  50719. this._setValue(target, this._originalValue[index], -1);
  50720. }
  50721. index++;
  50722. }
  50723. }
  50724. else {
  50725. if (this._originalValue[0] !== undefined) {
  50726. this._setValue(this._target, this._originalValue[0], -1);
  50727. }
  50728. }
  50729. }
  50730. this._offsetsCache = {};
  50731. this._highLimitsCache = {};
  50732. this._currentFrame = 0;
  50733. this._blendingFactor = 0;
  50734. this._originalValue = new Array();
  50735. // Events
  50736. for (var index = 0; index < this._events.length; index++) {
  50737. this._events[index].isDone = false;
  50738. }
  50739. };
  50740. /**
  50741. * Specifies if the runtime animation is stopped
  50742. * @returns Boolean specifying if the runtime animation is stopped
  50743. */
  50744. RuntimeAnimation.prototype.isStopped = function () {
  50745. return this._stopped;
  50746. };
  50747. /**
  50748. * Disposes of the runtime animation
  50749. */
  50750. RuntimeAnimation.prototype.dispose = function () {
  50751. var index = this._animation.runtimeAnimations.indexOf(this);
  50752. if (index > -1) {
  50753. this._animation.runtimeAnimations.splice(index, 1);
  50754. }
  50755. };
  50756. /**
  50757. * Interpolates the animation from the current frame
  50758. * @param currentFrame The frame to interpolate the animation to
  50759. * @param repeatCount The number of times that the animation should loop
  50760. * @param loopMode The type of looping mode to use
  50761. * @param offsetValue Animation offset value
  50762. * @param highLimitValue The high limit value
  50763. * @returns The interpolated value
  50764. */
  50765. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50766. this._currentFrame = currentFrame;
  50767. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50768. this._workValue = BABYLON.Matrix.Zero();
  50769. }
  50770. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50771. };
  50772. /**
  50773. * Apply the interpolated value to the target
  50774. * @param currentValue defines the value computed by the animation
  50775. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50776. */
  50777. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50778. if (weight === void 0) { weight = 1.0; }
  50779. if (this._target instanceof Array) {
  50780. var index = 0;
  50781. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50782. var target = _a[_i];
  50783. this._setValue(target, currentValue, weight, index);
  50784. index++;
  50785. }
  50786. }
  50787. else {
  50788. this._setValue(this._target, currentValue, weight);
  50789. }
  50790. };
  50791. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50792. if (targetIndex === void 0) { targetIndex = 0; }
  50793. // Set value
  50794. var path;
  50795. var destination;
  50796. var targetPropertyPath = this._animation.targetPropertyPath;
  50797. if (targetPropertyPath.length > 1) {
  50798. var property = target[targetPropertyPath[0]];
  50799. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50800. property = property[targetPropertyPath[index]];
  50801. }
  50802. path = targetPropertyPath[targetPropertyPath.length - 1];
  50803. destination = property;
  50804. }
  50805. else {
  50806. path = targetPropertyPath[0];
  50807. destination = target;
  50808. }
  50809. this._targetPath = path;
  50810. this._activeTarget = destination;
  50811. this._weight = weight;
  50812. if (this._originalValue[targetIndex] === undefined) {
  50813. var originalValue = void 0;
  50814. if (destination.getRestPose && path === "_matrix") { // For bones
  50815. originalValue = destination.getRestPose();
  50816. }
  50817. else {
  50818. originalValue = destination[path];
  50819. }
  50820. if (originalValue && originalValue.clone) {
  50821. this._originalValue[targetIndex] = originalValue.clone();
  50822. }
  50823. else {
  50824. this._originalValue[targetIndex] = originalValue;
  50825. }
  50826. }
  50827. // Blending
  50828. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50829. if (enableBlending && this._blendingFactor <= 1.0) {
  50830. if (!this._originalBlendValue) {
  50831. var originalValue = destination[path];
  50832. if (originalValue.clone) {
  50833. this._originalBlendValue = originalValue.clone();
  50834. }
  50835. else {
  50836. this._originalBlendValue = originalValue;
  50837. }
  50838. }
  50839. if (this._originalBlendValue.m) { // Matrix
  50840. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50841. if (this._currentValue) {
  50842. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50843. }
  50844. else {
  50845. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50846. }
  50847. }
  50848. else {
  50849. if (this._currentValue) {
  50850. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50851. }
  50852. else {
  50853. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50854. }
  50855. }
  50856. }
  50857. else {
  50858. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50859. }
  50860. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50861. this._blendingFactor += blendingSpeed;
  50862. }
  50863. else {
  50864. this._currentValue = currentValue;
  50865. }
  50866. if (weight !== -1.0) {
  50867. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50868. }
  50869. else {
  50870. destination[path] = this._currentValue;
  50871. }
  50872. if (target.markAsDirty) {
  50873. target.markAsDirty(this._animation.targetProperty);
  50874. }
  50875. };
  50876. /**
  50877. * Gets the loop pmode of the runtime animation
  50878. * @returns Loop Mode
  50879. */
  50880. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50881. if (this._target && this._target.animationPropertiesOverride) {
  50882. return this._target.animationPropertiesOverride.loopMode;
  50883. }
  50884. return this._animation.loopMode;
  50885. };
  50886. /**
  50887. * Move the current animation to a given frame
  50888. * @param frame defines the frame to move to
  50889. */
  50890. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50891. var keys = this._animation.getKeys();
  50892. if (frame < keys[0].frame) {
  50893. frame = keys[0].frame;
  50894. }
  50895. else if (frame > keys[keys.length - 1].frame) {
  50896. frame = keys[keys.length - 1].frame;
  50897. }
  50898. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50899. this.setValue(currentValue, -1);
  50900. };
  50901. /**
  50902. * @hidden Internal use only
  50903. */
  50904. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50905. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50906. this._ratioOffset = this._previousRatio - newRatio;
  50907. };
  50908. /**
  50909. * Execute the current animation
  50910. * @param delay defines the delay to add to the current frame
  50911. * @param from defines the lower bound of the animation range
  50912. * @param to defines the upper bound of the animation range
  50913. * @param loop defines if the current animation must loop
  50914. * @param speedRatio defines the current speed ratio
  50915. * @param weight defines the weight of the animation (default is -1 so no weight)
  50916. * @returns a boolean indicating if the animation is running
  50917. */
  50918. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50919. if (weight === void 0) { weight = -1.0; }
  50920. var targetPropertyPath = this._animation.targetPropertyPath;
  50921. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50922. this._stopped = true;
  50923. return false;
  50924. }
  50925. var returnValue = true;
  50926. var keys = this._animation.getKeys();
  50927. // Adding a start key at frame 0 if missing
  50928. if (keys[0].frame !== 0) {
  50929. var newKey = { frame: 0, value: keys[0].value };
  50930. keys.splice(0, 0, newKey);
  50931. }
  50932. // Adding a duplicate key when there is only one key at frame zero
  50933. else if (keys.length === 1) {
  50934. var newKey = { frame: 0.001, value: keys[0].value };
  50935. keys.push(newKey);
  50936. }
  50937. // Check limits
  50938. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50939. from = keys[0].frame;
  50940. }
  50941. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50942. to = keys[keys.length - 1].frame;
  50943. }
  50944. //to and from cannot be the same key
  50945. if (from === to) {
  50946. if (from > keys[0].frame) {
  50947. from--;
  50948. }
  50949. else if (to < keys[keys.length - 1].frame) {
  50950. to++;
  50951. }
  50952. }
  50953. // Compute ratio
  50954. var range = to - from;
  50955. var offsetValue;
  50956. // ratio represents the frame delta between from and to
  50957. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50958. var highLimitValue = 0;
  50959. this._previousDelay = delay;
  50960. this._previousRatio = ratio;
  50961. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  50962. returnValue = false;
  50963. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  50964. }
  50965. else {
  50966. // Get max value if required
  50967. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50968. var keyOffset = to.toString() + from.toString();
  50969. if (!this._offsetsCache[keyOffset]) {
  50970. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50971. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50972. switch (this._animation.dataType) {
  50973. // Float
  50974. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50975. this._offsetsCache[keyOffset] = toValue - fromValue;
  50976. break;
  50977. // Quaternion
  50978. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50979. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50980. break;
  50981. // Vector3
  50982. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50983. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50984. // Vector2
  50985. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50986. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50987. // Size
  50988. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50989. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50990. // Color3
  50991. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50992. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50993. default:
  50994. break;
  50995. }
  50996. this._highLimitsCache[keyOffset] = toValue;
  50997. }
  50998. highLimitValue = this._highLimitsCache[keyOffset];
  50999. offsetValue = this._offsetsCache[keyOffset];
  51000. }
  51001. }
  51002. if (offsetValue === undefined) {
  51003. switch (this._animation.dataType) {
  51004. // Float
  51005. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51006. offsetValue = 0;
  51007. break;
  51008. // Quaternion
  51009. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51010. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51011. break;
  51012. // Vector3
  51013. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51014. offsetValue = BABYLON.Vector3.Zero();
  51015. break;
  51016. // Vector2
  51017. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51018. offsetValue = BABYLON.Vector2.Zero();
  51019. break;
  51020. // Size
  51021. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51022. offsetValue = BABYLON.Size.Zero();
  51023. break;
  51024. // Color3
  51025. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51026. offsetValue = BABYLON.Color3.Black();
  51027. }
  51028. }
  51029. // Compute value
  51030. var repeatCount = (ratio / range) >> 0;
  51031. var currentFrame = returnValue ? from + ratio % range : to;
  51032. // Need to normalize?
  51033. if (this._host && this._host.syncRoot) {
  51034. var syncRoot = this._host.syncRoot;
  51035. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51036. currentFrame = from + (to - from) * hostNormalizedFrame;
  51037. }
  51038. // Reset events if looping
  51039. var events = this._events;
  51040. if (range > 0 && this.currentFrame > currentFrame ||
  51041. range < 0 && this.currentFrame < currentFrame) {
  51042. // Need to reset animation events
  51043. for (var index = 0; index < events.length; index++) {
  51044. if (!events[index].onlyOnce) {
  51045. // reset event, the animation is looping
  51046. events[index].isDone = false;
  51047. }
  51048. }
  51049. }
  51050. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51051. // Set value
  51052. this.setValue(currentValue, weight);
  51053. // Check events
  51054. for (var index = 0; index < events.length; index++) {
  51055. // Make sure current frame has passed event frame and that event frame is within the current range
  51056. // Also, handle both forward and reverse animations
  51057. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51058. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51059. var event = events[index];
  51060. if (!event.isDone) {
  51061. // If event should be done only once, remove it.
  51062. if (event.onlyOnce) {
  51063. events.splice(index, 1);
  51064. index--;
  51065. }
  51066. event.isDone = true;
  51067. event.action();
  51068. } // Don't do anything if the event has already be done.
  51069. }
  51070. }
  51071. if (!returnValue) {
  51072. this._stopped = true;
  51073. }
  51074. return returnValue;
  51075. };
  51076. return RuntimeAnimation;
  51077. }());
  51078. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51079. })(BABYLON || (BABYLON = {}));
  51080. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51081. var BABYLON;
  51082. (function (BABYLON) {
  51083. /**
  51084. * Class used to store an actual running animation
  51085. */
  51086. var Animatable = /** @class */ (function () {
  51087. /**
  51088. * Creates a new Animatable
  51089. * @param scene defines the hosting scene
  51090. * @param target defines the target object
  51091. * @param fromFrame defines the starting frame number (default is 0)
  51092. * @param toFrame defines the ending frame number (default is 100)
  51093. * @param loopAnimation defines if the animation must loop (default is false)
  51094. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51095. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51096. * @param animations defines a group of animation to add to the new Animatable
  51097. */
  51098. function Animatable(scene,
  51099. /** defines the target object */
  51100. target,
  51101. /** defines the starting frame number (default is 0) */
  51102. fromFrame,
  51103. /** defines the ending frame number (default is 100) */
  51104. toFrame,
  51105. /** defines if the animation must loop (default is false) */
  51106. loopAnimation, speedRatio,
  51107. /** defines a callback to call when animation ends if it is not looping */
  51108. onAnimationEnd, animations) {
  51109. if (fromFrame === void 0) { fromFrame = 0; }
  51110. if (toFrame === void 0) { toFrame = 100; }
  51111. if (loopAnimation === void 0) { loopAnimation = false; }
  51112. if (speedRatio === void 0) { speedRatio = 1.0; }
  51113. this.target = target;
  51114. this.fromFrame = fromFrame;
  51115. this.toFrame = toFrame;
  51116. this.loopAnimation = loopAnimation;
  51117. this.onAnimationEnd = onAnimationEnd;
  51118. this._localDelayOffset = null;
  51119. this._pausedDelay = null;
  51120. this._runtimeAnimations = new Array();
  51121. this._paused = false;
  51122. this._speedRatio = 1;
  51123. this._weight = -1.0;
  51124. /**
  51125. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51126. * This will only apply for non looping animation (default is true)
  51127. */
  51128. this.disposeOnEnd = true;
  51129. /**
  51130. * Gets a boolean indicating if the animation has started
  51131. */
  51132. this.animationStarted = false;
  51133. /**
  51134. * Observer raised when the animation ends
  51135. */
  51136. this.onAnimationEndObservable = new BABYLON.Observable();
  51137. this._scene = scene;
  51138. if (animations) {
  51139. this.appendAnimations(target, animations);
  51140. }
  51141. this._speedRatio = speedRatio;
  51142. scene._activeAnimatables.push(this);
  51143. }
  51144. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51145. /**
  51146. * Gets the root Animatable used to synchronize and normalize animations
  51147. */
  51148. get: function () {
  51149. return this._syncRoot;
  51150. },
  51151. enumerable: true,
  51152. configurable: true
  51153. });
  51154. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51155. /**
  51156. * Gets the current frame of the first RuntimeAnimation
  51157. * Used to synchronize Animatables
  51158. */
  51159. get: function () {
  51160. if (this._runtimeAnimations.length === 0) {
  51161. return 0;
  51162. }
  51163. return this._runtimeAnimations[0].currentFrame;
  51164. },
  51165. enumerable: true,
  51166. configurable: true
  51167. });
  51168. Object.defineProperty(Animatable.prototype, "weight", {
  51169. /**
  51170. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51171. */
  51172. get: function () {
  51173. return this._weight;
  51174. },
  51175. set: function (value) {
  51176. if (value === -1) { // -1 is ok and means no weight
  51177. this._weight = -1;
  51178. return;
  51179. }
  51180. // Else weight must be in [0, 1] range
  51181. this._weight = Math.min(Math.max(value, 0), 1.0);
  51182. },
  51183. enumerable: true,
  51184. configurable: true
  51185. });
  51186. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51187. /**
  51188. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51189. */
  51190. get: function () {
  51191. return this._speedRatio;
  51192. },
  51193. set: function (value) {
  51194. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51195. var animation = this._runtimeAnimations[index];
  51196. animation._prepareForSpeedRatioChange(value);
  51197. }
  51198. this._speedRatio = value;
  51199. },
  51200. enumerable: true,
  51201. configurable: true
  51202. });
  51203. // Methods
  51204. /**
  51205. * Synchronize and normalize current Animatable with a source Animatable
  51206. * This is useful when using animation weights and when animations are not of the same length
  51207. * @param root defines the root Animatable to synchronize with
  51208. * @returns the current Animatable
  51209. */
  51210. Animatable.prototype.syncWith = function (root) {
  51211. this._syncRoot = root;
  51212. if (root) {
  51213. // Make sure this animatable will animate after the root
  51214. var index = this._scene._activeAnimatables.indexOf(this);
  51215. if (index > -1) {
  51216. this._scene._activeAnimatables.splice(index, 1);
  51217. this._scene._activeAnimatables.push(this);
  51218. }
  51219. }
  51220. return this;
  51221. };
  51222. /**
  51223. * Gets the list of runtime animations
  51224. * @returns an array of RuntimeAnimation
  51225. */
  51226. Animatable.prototype.getAnimations = function () {
  51227. return this._runtimeAnimations;
  51228. };
  51229. /**
  51230. * Adds more animations to the current animatable
  51231. * @param target defines the target of the animations
  51232. * @param animations defines the new animations to add
  51233. */
  51234. Animatable.prototype.appendAnimations = function (target, animations) {
  51235. for (var index = 0; index < animations.length; index++) {
  51236. var animation = animations[index];
  51237. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51238. }
  51239. };
  51240. /**
  51241. * Gets the source animation for a specific property
  51242. * @param property defines the propertyu to look for
  51243. * @returns null or the source animation for the given property
  51244. */
  51245. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51246. var runtimeAnimations = this._runtimeAnimations;
  51247. for (var index = 0; index < runtimeAnimations.length; index++) {
  51248. if (runtimeAnimations[index].animation.targetProperty === property) {
  51249. return runtimeAnimations[index].animation;
  51250. }
  51251. }
  51252. return null;
  51253. };
  51254. /**
  51255. * Gets the runtime animation for a specific property
  51256. * @param property defines the propertyu to look for
  51257. * @returns null or the runtime animation for the given property
  51258. */
  51259. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51260. var runtimeAnimations = this._runtimeAnimations;
  51261. for (var index = 0; index < runtimeAnimations.length; index++) {
  51262. if (runtimeAnimations[index].animation.targetProperty === property) {
  51263. return runtimeAnimations[index];
  51264. }
  51265. }
  51266. return null;
  51267. };
  51268. /**
  51269. * Resets the animatable to its original state
  51270. */
  51271. Animatable.prototype.reset = function () {
  51272. var runtimeAnimations = this._runtimeAnimations;
  51273. for (var index = 0; index < runtimeAnimations.length; index++) {
  51274. runtimeAnimations[index].reset(true);
  51275. }
  51276. this._localDelayOffset = null;
  51277. this._pausedDelay = null;
  51278. };
  51279. /**
  51280. * Allows the animatable to blend with current running animations
  51281. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51282. * @param blendingSpeed defines the blending speed to use
  51283. */
  51284. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51285. var runtimeAnimations = this._runtimeAnimations;
  51286. for (var index = 0; index < runtimeAnimations.length; index++) {
  51287. runtimeAnimations[index].animation.enableBlending = true;
  51288. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51289. }
  51290. };
  51291. /**
  51292. * Disable animation blending
  51293. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51294. */
  51295. Animatable.prototype.disableBlending = function () {
  51296. var runtimeAnimations = this._runtimeAnimations;
  51297. for (var index = 0; index < runtimeAnimations.length; index++) {
  51298. runtimeAnimations[index].animation.enableBlending = false;
  51299. }
  51300. };
  51301. /**
  51302. * Jump directly to a given frame
  51303. * @param frame defines the frame to jump to
  51304. */
  51305. Animatable.prototype.goToFrame = function (frame) {
  51306. var runtimeAnimations = this._runtimeAnimations;
  51307. if (runtimeAnimations[0]) {
  51308. var fps = runtimeAnimations[0].animation.framePerSecond;
  51309. var currentFrame = runtimeAnimations[0].currentFrame;
  51310. var adjustTime = frame - currentFrame;
  51311. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51312. if (this._localDelayOffset === null) {
  51313. this._localDelayOffset = 0;
  51314. }
  51315. this._localDelayOffset -= delay;
  51316. }
  51317. for (var index = 0; index < runtimeAnimations.length; index++) {
  51318. runtimeAnimations[index].goToFrame(frame);
  51319. }
  51320. };
  51321. /**
  51322. * Pause the animation
  51323. */
  51324. Animatable.prototype.pause = function () {
  51325. if (this._paused) {
  51326. return;
  51327. }
  51328. this._paused = true;
  51329. };
  51330. /**
  51331. * Restart the animation
  51332. */
  51333. Animatable.prototype.restart = function () {
  51334. this._paused = false;
  51335. };
  51336. Animatable.prototype._raiseOnAnimationEnd = function () {
  51337. if (this.onAnimationEnd) {
  51338. this.onAnimationEnd();
  51339. }
  51340. this.onAnimationEndObservable.notifyObservers(this);
  51341. };
  51342. /**
  51343. * Stop and delete the current animation
  51344. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51345. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  51346. */
  51347. Animatable.prototype.stop = function (animationName, targetMask) {
  51348. if (animationName || targetMask) {
  51349. var idx = this._scene._activeAnimatables.indexOf(this);
  51350. if (idx > -1) {
  51351. var runtimeAnimations = this._runtimeAnimations;
  51352. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51353. var runtimeAnimation = runtimeAnimations[index];
  51354. if (animationName && runtimeAnimation.animation.name != animationName) {
  51355. continue;
  51356. }
  51357. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51358. continue;
  51359. }
  51360. runtimeAnimation.dispose();
  51361. runtimeAnimations.splice(index, 1);
  51362. }
  51363. if (runtimeAnimations.length == 0) {
  51364. this._scene._activeAnimatables.splice(idx, 1);
  51365. this._raiseOnAnimationEnd();
  51366. }
  51367. }
  51368. }
  51369. else {
  51370. var index = this._scene._activeAnimatables.indexOf(this);
  51371. if (index > -1) {
  51372. this._scene._activeAnimatables.splice(index, 1);
  51373. var runtimeAnimations = this._runtimeAnimations;
  51374. for (var index = 0; index < runtimeAnimations.length; index++) {
  51375. runtimeAnimations[index].dispose();
  51376. }
  51377. this._raiseOnAnimationEnd();
  51378. }
  51379. }
  51380. };
  51381. /**
  51382. * Wait asynchronously for the animation to end
  51383. * @returns a promise which will be fullfilled when the animation ends
  51384. */
  51385. Animatable.prototype.waitAsync = function () {
  51386. var _this = this;
  51387. return new Promise(function (resolve, reject) {
  51388. _this.onAnimationEndObservable.add(function () {
  51389. resolve(_this);
  51390. }, undefined, undefined, _this, true);
  51391. });
  51392. };
  51393. /** @hidden */
  51394. Animatable.prototype._animate = function (delay) {
  51395. if (this._paused) {
  51396. this.animationStarted = false;
  51397. if (this._pausedDelay === null) {
  51398. this._pausedDelay = delay;
  51399. }
  51400. return true;
  51401. }
  51402. if (this._localDelayOffset === null) {
  51403. this._localDelayOffset = delay;
  51404. this._pausedDelay = null;
  51405. }
  51406. else if (this._pausedDelay !== null) {
  51407. this._localDelayOffset += delay - this._pausedDelay;
  51408. this._pausedDelay = null;
  51409. }
  51410. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51411. return true;
  51412. }
  51413. // Animating
  51414. var running = false;
  51415. var runtimeAnimations = this._runtimeAnimations;
  51416. var index;
  51417. for (index = 0; index < runtimeAnimations.length; index++) {
  51418. var animation = runtimeAnimations[index];
  51419. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51420. running = running || isRunning;
  51421. }
  51422. this.animationStarted = running;
  51423. if (!running) {
  51424. if (this.disposeOnEnd) {
  51425. // Remove from active animatables
  51426. index = this._scene._activeAnimatables.indexOf(this);
  51427. this._scene._activeAnimatables.splice(index, 1);
  51428. // Dispose all runtime animations
  51429. for (index = 0; index < runtimeAnimations.length; index++) {
  51430. runtimeAnimations[index].dispose();
  51431. }
  51432. }
  51433. this._raiseOnAnimationEnd();
  51434. if (this.disposeOnEnd) {
  51435. this.onAnimationEnd = null;
  51436. this.onAnimationEndObservable.clear();
  51437. }
  51438. }
  51439. return running;
  51440. };
  51441. return Animatable;
  51442. }());
  51443. BABYLON.Animatable = Animatable;
  51444. })(BABYLON || (BABYLON = {}));
  51445. //# sourceMappingURL=babylon.animatable.js.map
  51446. var BABYLON;
  51447. (function (BABYLON) {
  51448. var EasingFunction = /** @class */ (function () {
  51449. function EasingFunction() {
  51450. // Properties
  51451. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51452. }
  51453. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51454. get: function () {
  51455. return EasingFunction._EASINGMODE_EASEIN;
  51456. },
  51457. enumerable: true,
  51458. configurable: true
  51459. });
  51460. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51461. get: function () {
  51462. return EasingFunction._EASINGMODE_EASEOUT;
  51463. },
  51464. enumerable: true,
  51465. configurable: true
  51466. });
  51467. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51468. get: function () {
  51469. return EasingFunction._EASINGMODE_EASEINOUT;
  51470. },
  51471. enumerable: true,
  51472. configurable: true
  51473. });
  51474. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51475. var n = Math.min(Math.max(easingMode, 0), 2);
  51476. this._easingMode = n;
  51477. };
  51478. EasingFunction.prototype.getEasingMode = function () {
  51479. return this._easingMode;
  51480. };
  51481. EasingFunction.prototype.easeInCore = function (gradient) {
  51482. throw new Error('You must implement this method');
  51483. };
  51484. EasingFunction.prototype.ease = function (gradient) {
  51485. switch (this._easingMode) {
  51486. case EasingFunction.EASINGMODE_EASEIN:
  51487. return this.easeInCore(gradient);
  51488. case EasingFunction.EASINGMODE_EASEOUT:
  51489. return (1 - this.easeInCore(1 - gradient));
  51490. }
  51491. if (gradient >= 0.5) {
  51492. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51493. }
  51494. return (this.easeInCore(gradient * 2) * 0.5);
  51495. };
  51496. //Statics
  51497. EasingFunction._EASINGMODE_EASEIN = 0;
  51498. EasingFunction._EASINGMODE_EASEOUT = 1;
  51499. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51500. return EasingFunction;
  51501. }());
  51502. BABYLON.EasingFunction = EasingFunction;
  51503. var CircleEase = /** @class */ (function (_super) {
  51504. __extends(CircleEase, _super);
  51505. function CircleEase() {
  51506. return _super !== null && _super.apply(this, arguments) || this;
  51507. }
  51508. CircleEase.prototype.easeInCore = function (gradient) {
  51509. gradient = Math.max(0, Math.min(1, gradient));
  51510. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51511. };
  51512. return CircleEase;
  51513. }(EasingFunction));
  51514. BABYLON.CircleEase = CircleEase;
  51515. var BackEase = /** @class */ (function (_super) {
  51516. __extends(BackEase, _super);
  51517. function BackEase(amplitude) {
  51518. if (amplitude === void 0) { amplitude = 1; }
  51519. var _this = _super.call(this) || this;
  51520. _this.amplitude = amplitude;
  51521. return _this;
  51522. }
  51523. BackEase.prototype.easeInCore = function (gradient) {
  51524. var num = Math.max(0, this.amplitude);
  51525. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51526. };
  51527. return BackEase;
  51528. }(EasingFunction));
  51529. BABYLON.BackEase = BackEase;
  51530. var BounceEase = /** @class */ (function (_super) {
  51531. __extends(BounceEase, _super);
  51532. function BounceEase(bounces, bounciness) {
  51533. if (bounces === void 0) { bounces = 3; }
  51534. if (bounciness === void 0) { bounciness = 2; }
  51535. var _this = _super.call(this) || this;
  51536. _this.bounces = bounces;
  51537. _this.bounciness = bounciness;
  51538. return _this;
  51539. }
  51540. BounceEase.prototype.easeInCore = function (gradient) {
  51541. var y = Math.max(0.0, this.bounces);
  51542. var bounciness = this.bounciness;
  51543. if (bounciness <= 1.0) {
  51544. bounciness = 1.001;
  51545. }
  51546. var num9 = Math.pow(bounciness, y);
  51547. var num5 = 1.0 - bounciness;
  51548. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51549. var num15 = gradient * num4;
  51550. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51551. var num3 = Math.floor(num65);
  51552. var num13 = num3 + 1.0;
  51553. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51554. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51555. var num7 = (num8 + num12) * 0.5;
  51556. var num6 = gradient - num7;
  51557. var num2 = num7 - num8;
  51558. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51559. };
  51560. return BounceEase;
  51561. }(EasingFunction));
  51562. BABYLON.BounceEase = BounceEase;
  51563. var CubicEase = /** @class */ (function (_super) {
  51564. __extends(CubicEase, _super);
  51565. function CubicEase() {
  51566. return _super !== null && _super.apply(this, arguments) || this;
  51567. }
  51568. CubicEase.prototype.easeInCore = function (gradient) {
  51569. return (gradient * gradient * gradient);
  51570. };
  51571. return CubicEase;
  51572. }(EasingFunction));
  51573. BABYLON.CubicEase = CubicEase;
  51574. var ElasticEase = /** @class */ (function (_super) {
  51575. __extends(ElasticEase, _super);
  51576. function ElasticEase(oscillations, springiness) {
  51577. if (oscillations === void 0) { oscillations = 3; }
  51578. if (springiness === void 0) { springiness = 3; }
  51579. var _this = _super.call(this) || this;
  51580. _this.oscillations = oscillations;
  51581. _this.springiness = springiness;
  51582. return _this;
  51583. }
  51584. ElasticEase.prototype.easeInCore = function (gradient) {
  51585. var num2;
  51586. var num3 = Math.max(0.0, this.oscillations);
  51587. var num = Math.max(0.0, this.springiness);
  51588. if (num == 0) {
  51589. num2 = gradient;
  51590. }
  51591. else {
  51592. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51593. }
  51594. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51595. };
  51596. return ElasticEase;
  51597. }(EasingFunction));
  51598. BABYLON.ElasticEase = ElasticEase;
  51599. var ExponentialEase = /** @class */ (function (_super) {
  51600. __extends(ExponentialEase, _super);
  51601. function ExponentialEase(exponent) {
  51602. if (exponent === void 0) { exponent = 2; }
  51603. var _this = _super.call(this) || this;
  51604. _this.exponent = exponent;
  51605. return _this;
  51606. }
  51607. ExponentialEase.prototype.easeInCore = function (gradient) {
  51608. if (this.exponent <= 0) {
  51609. return gradient;
  51610. }
  51611. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51612. };
  51613. return ExponentialEase;
  51614. }(EasingFunction));
  51615. BABYLON.ExponentialEase = ExponentialEase;
  51616. var PowerEase = /** @class */ (function (_super) {
  51617. __extends(PowerEase, _super);
  51618. function PowerEase(power) {
  51619. if (power === void 0) { power = 2; }
  51620. var _this = _super.call(this) || this;
  51621. _this.power = power;
  51622. return _this;
  51623. }
  51624. PowerEase.prototype.easeInCore = function (gradient) {
  51625. var y = Math.max(0.0, this.power);
  51626. return Math.pow(gradient, y);
  51627. };
  51628. return PowerEase;
  51629. }(EasingFunction));
  51630. BABYLON.PowerEase = PowerEase;
  51631. var QuadraticEase = /** @class */ (function (_super) {
  51632. __extends(QuadraticEase, _super);
  51633. function QuadraticEase() {
  51634. return _super !== null && _super.apply(this, arguments) || this;
  51635. }
  51636. QuadraticEase.prototype.easeInCore = function (gradient) {
  51637. return (gradient * gradient);
  51638. };
  51639. return QuadraticEase;
  51640. }(EasingFunction));
  51641. BABYLON.QuadraticEase = QuadraticEase;
  51642. var QuarticEase = /** @class */ (function (_super) {
  51643. __extends(QuarticEase, _super);
  51644. function QuarticEase() {
  51645. return _super !== null && _super.apply(this, arguments) || this;
  51646. }
  51647. QuarticEase.prototype.easeInCore = function (gradient) {
  51648. return (gradient * gradient * gradient * gradient);
  51649. };
  51650. return QuarticEase;
  51651. }(EasingFunction));
  51652. BABYLON.QuarticEase = QuarticEase;
  51653. var QuinticEase = /** @class */ (function (_super) {
  51654. __extends(QuinticEase, _super);
  51655. function QuinticEase() {
  51656. return _super !== null && _super.apply(this, arguments) || this;
  51657. }
  51658. QuinticEase.prototype.easeInCore = function (gradient) {
  51659. return (gradient * gradient * gradient * gradient * gradient);
  51660. };
  51661. return QuinticEase;
  51662. }(EasingFunction));
  51663. BABYLON.QuinticEase = QuinticEase;
  51664. var SineEase = /** @class */ (function (_super) {
  51665. __extends(SineEase, _super);
  51666. function SineEase() {
  51667. return _super !== null && _super.apply(this, arguments) || this;
  51668. }
  51669. SineEase.prototype.easeInCore = function (gradient) {
  51670. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51671. };
  51672. return SineEase;
  51673. }(EasingFunction));
  51674. BABYLON.SineEase = SineEase;
  51675. var BezierCurveEase = /** @class */ (function (_super) {
  51676. __extends(BezierCurveEase, _super);
  51677. function BezierCurveEase(x1, y1, x2, y2) {
  51678. if (x1 === void 0) { x1 = 0; }
  51679. if (y1 === void 0) { y1 = 0; }
  51680. if (x2 === void 0) { x2 = 1; }
  51681. if (y2 === void 0) { y2 = 1; }
  51682. var _this = _super.call(this) || this;
  51683. _this.x1 = x1;
  51684. _this.y1 = y1;
  51685. _this.x2 = x2;
  51686. _this.y2 = y2;
  51687. return _this;
  51688. }
  51689. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51690. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51691. };
  51692. return BezierCurveEase;
  51693. }(EasingFunction));
  51694. BABYLON.BezierCurveEase = BezierCurveEase;
  51695. })(BABYLON || (BABYLON = {}));
  51696. //# sourceMappingURL=babylon.easing.js.map
  51697. var BABYLON;
  51698. (function (BABYLON) {
  51699. /**
  51700. * A Condition applied to an Action
  51701. */
  51702. var Condition = /** @class */ (function () {
  51703. /**
  51704. * Creates a new Condition
  51705. * @param actionManager the manager of the action the condition is applied to
  51706. */
  51707. function Condition(actionManager) {
  51708. this._actionManager = actionManager;
  51709. }
  51710. /**
  51711. * Check if the current condition is valid
  51712. * @returns a boolean
  51713. */
  51714. Condition.prototype.isValid = function () {
  51715. return true;
  51716. };
  51717. /**
  51718. * Internal only
  51719. * @hidden
  51720. */
  51721. Condition.prototype._getProperty = function (propertyPath) {
  51722. return this._actionManager._getProperty(propertyPath);
  51723. };
  51724. /**
  51725. * Internal only
  51726. * @hidden
  51727. */
  51728. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51729. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51730. };
  51731. /**
  51732. * Serialize placeholder for child classes
  51733. * @returns the serialized object
  51734. */
  51735. Condition.prototype.serialize = function () {
  51736. };
  51737. /**
  51738. * Internal only
  51739. * @hidden
  51740. */
  51741. Condition.prototype._serialize = function (serializedCondition) {
  51742. return {
  51743. type: 2,
  51744. children: [],
  51745. name: serializedCondition.name,
  51746. properties: serializedCondition.properties
  51747. };
  51748. };
  51749. return Condition;
  51750. }());
  51751. BABYLON.Condition = Condition;
  51752. /**
  51753. * Defines specific conditional operators as extensions of Condition
  51754. */
  51755. var ValueCondition = /** @class */ (function (_super) {
  51756. __extends(ValueCondition, _super);
  51757. /**
  51758. * Creates a new ValueCondition
  51759. * @param actionManager manager for the action the condition applies to
  51760. * @param target for the action
  51761. * @param propertyPath path to specify the property of the target the conditional operator uses
  51762. * @param value the value compared by the conditional operator against the current value of the property
  51763. * @param operator the conditional operator, default ValueCondition.IsEqual
  51764. */
  51765. function ValueCondition(actionManager, target,
  51766. /** path to specify the property of the target the conditional operator uses */
  51767. propertyPath,
  51768. /** the value compared by the conditional operator against the current value of the property */
  51769. value,
  51770. /** the conditional operator, default ValueCondition.IsEqual */
  51771. operator) {
  51772. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51773. var _this = _super.call(this, actionManager) || this;
  51774. _this.propertyPath = propertyPath;
  51775. _this.value = value;
  51776. _this.operator = operator;
  51777. _this._target = target;
  51778. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51779. _this._property = _this._getProperty(_this.propertyPath);
  51780. return _this;
  51781. }
  51782. Object.defineProperty(ValueCondition, "IsEqual", {
  51783. /**
  51784. * returns the number for IsEqual
  51785. */
  51786. get: function () {
  51787. return ValueCondition._IsEqual;
  51788. },
  51789. enumerable: true,
  51790. configurable: true
  51791. });
  51792. Object.defineProperty(ValueCondition, "IsDifferent", {
  51793. /**
  51794. * Returns the number for IsDifferent
  51795. */
  51796. get: function () {
  51797. return ValueCondition._IsDifferent;
  51798. },
  51799. enumerable: true,
  51800. configurable: true
  51801. });
  51802. Object.defineProperty(ValueCondition, "IsGreater", {
  51803. /**
  51804. * Returns the number for IsGreater
  51805. */
  51806. get: function () {
  51807. return ValueCondition._IsGreater;
  51808. },
  51809. enumerable: true,
  51810. configurable: true
  51811. });
  51812. Object.defineProperty(ValueCondition, "IsLesser", {
  51813. /**
  51814. * Returns the number for IsLesser
  51815. */
  51816. get: function () {
  51817. return ValueCondition._IsLesser;
  51818. },
  51819. enumerable: true,
  51820. configurable: true
  51821. });
  51822. /**
  51823. * Compares the given value with the property value for the specified conditional operator
  51824. * @returns the result of the comparison
  51825. */
  51826. ValueCondition.prototype.isValid = function () {
  51827. switch (this.operator) {
  51828. case ValueCondition.IsGreater:
  51829. return this._effectiveTarget[this._property] > this.value;
  51830. case ValueCondition.IsLesser:
  51831. return this._effectiveTarget[this._property] < this.value;
  51832. case ValueCondition.IsEqual:
  51833. case ValueCondition.IsDifferent:
  51834. var check;
  51835. if (this.value.equals) {
  51836. check = this.value.equals(this._effectiveTarget[this._property]);
  51837. }
  51838. else {
  51839. check = this.value === this._effectiveTarget[this._property];
  51840. }
  51841. return this.operator === ValueCondition.IsEqual ? check : !check;
  51842. }
  51843. return false;
  51844. };
  51845. /**
  51846. * Serialize the ValueCondition into a JSON compatible object
  51847. * @returns serialization object
  51848. */
  51849. ValueCondition.prototype.serialize = function () {
  51850. return this._serialize({
  51851. name: "ValueCondition",
  51852. properties: [
  51853. BABYLON.Action._GetTargetProperty(this._target),
  51854. { name: "propertyPath", value: this.propertyPath },
  51855. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51856. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51857. ]
  51858. });
  51859. };
  51860. /**
  51861. * Gets the name of the conditional operator for the ValueCondition
  51862. * @param operator the conditional operator
  51863. * @returns the name
  51864. */
  51865. ValueCondition.GetOperatorName = function (operator) {
  51866. switch (operator) {
  51867. case ValueCondition._IsEqual: return "IsEqual";
  51868. case ValueCondition._IsDifferent: return "IsDifferent";
  51869. case ValueCondition._IsGreater: return "IsGreater";
  51870. case ValueCondition._IsLesser: return "IsLesser";
  51871. default: return "";
  51872. }
  51873. };
  51874. /**
  51875. * Internal only
  51876. * @hidden
  51877. */
  51878. ValueCondition._IsEqual = 0;
  51879. /**
  51880. * Internal only
  51881. * @hidden
  51882. */
  51883. ValueCondition._IsDifferent = 1;
  51884. /**
  51885. * Internal only
  51886. * @hidden
  51887. */
  51888. ValueCondition._IsGreater = 2;
  51889. /**
  51890. * Internal only
  51891. * @hidden
  51892. */
  51893. ValueCondition._IsLesser = 3;
  51894. return ValueCondition;
  51895. }(Condition));
  51896. BABYLON.ValueCondition = ValueCondition;
  51897. /**
  51898. * Defines a predicate condition as an extension of Condition
  51899. */
  51900. var PredicateCondition = /** @class */ (function (_super) {
  51901. __extends(PredicateCondition, _super);
  51902. /**
  51903. * Creates a new PredicateCondition
  51904. * @param actionManager manager for the action the condition applies to
  51905. * @param predicate defines the predicate function used to validate the condition
  51906. */
  51907. function PredicateCondition(actionManager,
  51908. /** defines the predicate function used to validate the condition */
  51909. predicate) {
  51910. var _this = _super.call(this, actionManager) || this;
  51911. _this.predicate = predicate;
  51912. return _this;
  51913. }
  51914. /**
  51915. * @returns the validity of the predicate condition
  51916. */
  51917. PredicateCondition.prototype.isValid = function () {
  51918. return this.predicate();
  51919. };
  51920. return PredicateCondition;
  51921. }(Condition));
  51922. BABYLON.PredicateCondition = PredicateCondition;
  51923. /**
  51924. * Defines a state condition as an extension of Condition
  51925. */
  51926. var StateCondition = /** @class */ (function (_super) {
  51927. __extends(StateCondition, _super);
  51928. /**
  51929. * Creates a new StateCondition
  51930. * @param actionManager manager for the action the condition applies to
  51931. * @param target of the condition
  51932. * @param value to compare with target state
  51933. */
  51934. function StateCondition(actionManager, target, value) {
  51935. var _this = _super.call(this, actionManager) || this;
  51936. _this.value = value;
  51937. _this._target = target;
  51938. return _this;
  51939. }
  51940. /**
  51941. * @returns the validity of the state
  51942. */
  51943. StateCondition.prototype.isValid = function () {
  51944. return this._target.state === this.value;
  51945. };
  51946. /**
  51947. * Serialize the StateCondition into a JSON compatible object
  51948. * @returns serialization object
  51949. */
  51950. StateCondition.prototype.serialize = function () {
  51951. return this._serialize({
  51952. name: "StateCondition",
  51953. properties: [
  51954. BABYLON.Action._GetTargetProperty(this._target),
  51955. { name: "value", value: this.value }
  51956. ]
  51957. });
  51958. };
  51959. return StateCondition;
  51960. }(Condition));
  51961. BABYLON.StateCondition = StateCondition;
  51962. })(BABYLON || (BABYLON = {}));
  51963. //# sourceMappingURL=babylon.condition.js.map
  51964. var BABYLON;
  51965. (function (BABYLON) {
  51966. /**
  51967. * The action to be carried out following a trigger
  51968. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51969. */
  51970. var Action = /** @class */ (function () {
  51971. /**
  51972. * Creates a new Action
  51973. * @param triggerOptions the trigger, with or without parameters, for the action
  51974. * @param condition an optional determinant of action
  51975. */
  51976. function Action(
  51977. /** the trigger, with or without parameters, for the action */
  51978. triggerOptions, condition) {
  51979. this.triggerOptions = triggerOptions;
  51980. /**
  51981. * An event triggered prior to action being executed.
  51982. */
  51983. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51984. if (triggerOptions.parameter) {
  51985. this.trigger = triggerOptions.trigger;
  51986. this._triggerParameter = triggerOptions.parameter;
  51987. }
  51988. else {
  51989. this.trigger = triggerOptions;
  51990. }
  51991. this._nextActiveAction = this;
  51992. this._condition = condition;
  51993. }
  51994. /**
  51995. * Internal only
  51996. * @hidden
  51997. */
  51998. Action.prototype._prepare = function () {
  51999. };
  52000. /**
  52001. * Gets the trigger parameters
  52002. * @returns the trigger parameters
  52003. */
  52004. Action.prototype.getTriggerParameter = function () {
  52005. return this._triggerParameter;
  52006. };
  52007. /**
  52008. * Internal only - executes current action event
  52009. * @hidden
  52010. */
  52011. Action.prototype._executeCurrent = function (evt) {
  52012. if (this._nextActiveAction._condition) {
  52013. var condition = this._nextActiveAction._condition;
  52014. var currentRenderId = this._actionManager.getScene().getRenderId();
  52015. // We cache the current evaluation for the current frame
  52016. if (condition._evaluationId === currentRenderId) {
  52017. if (!condition._currentResult) {
  52018. return;
  52019. }
  52020. }
  52021. else {
  52022. condition._evaluationId = currentRenderId;
  52023. if (!condition.isValid()) {
  52024. condition._currentResult = false;
  52025. return;
  52026. }
  52027. condition._currentResult = true;
  52028. }
  52029. }
  52030. this.onBeforeExecuteObservable.notifyObservers(this);
  52031. this._nextActiveAction.execute(evt);
  52032. this.skipToNextActiveAction();
  52033. };
  52034. /**
  52035. * Execute placeholder for child classes
  52036. * @param evt optional action event
  52037. */
  52038. Action.prototype.execute = function (evt) {
  52039. };
  52040. /**
  52041. * Skips to next active action
  52042. */
  52043. Action.prototype.skipToNextActiveAction = function () {
  52044. if (this._nextActiveAction._child) {
  52045. if (!this._nextActiveAction._child._actionManager) {
  52046. this._nextActiveAction._child._actionManager = this._actionManager;
  52047. }
  52048. this._nextActiveAction = this._nextActiveAction._child;
  52049. }
  52050. else {
  52051. this._nextActiveAction = this;
  52052. }
  52053. };
  52054. /**
  52055. * Adds action to chain of actions, may be a DoNothingAction
  52056. * @param action defines the next action to execute
  52057. * @returns The action passed in
  52058. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52059. */
  52060. Action.prototype.then = function (action) {
  52061. this._child = action;
  52062. action._actionManager = this._actionManager;
  52063. action._prepare();
  52064. return action;
  52065. };
  52066. /**
  52067. * Internal only
  52068. * @hidden
  52069. */
  52070. Action.prototype._getProperty = function (propertyPath) {
  52071. return this._actionManager._getProperty(propertyPath);
  52072. };
  52073. /**
  52074. * Internal only
  52075. * @hidden
  52076. */
  52077. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52078. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52079. };
  52080. /**
  52081. * Serialize placeholder for child classes
  52082. * @param parent of child
  52083. * @returns the serialized object
  52084. */
  52085. Action.prototype.serialize = function (parent) {
  52086. };
  52087. /**
  52088. * Internal only called by serialize
  52089. * @hidden
  52090. */
  52091. Action.prototype._serialize = function (serializedAction, parent) {
  52092. var serializationObject = {
  52093. type: 1,
  52094. children: [],
  52095. name: serializedAction.name,
  52096. properties: serializedAction.properties || []
  52097. };
  52098. // Serialize child
  52099. if (this._child) {
  52100. this._child.serialize(serializationObject);
  52101. }
  52102. // Check if "this" has a condition
  52103. if (this._condition) {
  52104. var serializedCondition = this._condition.serialize();
  52105. serializedCondition.children.push(serializationObject);
  52106. if (parent) {
  52107. parent.children.push(serializedCondition);
  52108. }
  52109. return serializedCondition;
  52110. }
  52111. if (parent) {
  52112. parent.children.push(serializationObject);
  52113. }
  52114. return serializationObject;
  52115. };
  52116. /**
  52117. * Internal only
  52118. * @hidden
  52119. */
  52120. Action._SerializeValueAsString = function (value) {
  52121. if (typeof value === "number") {
  52122. return value.toString();
  52123. }
  52124. if (typeof value === "boolean") {
  52125. return value ? "true" : "false";
  52126. }
  52127. if (value instanceof BABYLON.Vector2) {
  52128. return value.x + ", " + value.y;
  52129. }
  52130. if (value instanceof BABYLON.Vector3) {
  52131. return value.x + ", " + value.y + ", " + value.z;
  52132. }
  52133. if (value instanceof BABYLON.Color3) {
  52134. return value.r + ", " + value.g + ", " + value.b;
  52135. }
  52136. if (value instanceof BABYLON.Color4) {
  52137. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52138. }
  52139. return value; // string
  52140. };
  52141. /**
  52142. * Internal only
  52143. * @hidden
  52144. */
  52145. Action._GetTargetProperty = function (target) {
  52146. return {
  52147. name: "target",
  52148. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52149. : target instanceof BABYLON.Light ? "LightProperties"
  52150. : target instanceof BABYLON.Camera ? "CameraProperties"
  52151. : "SceneProperties",
  52152. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52153. };
  52154. };
  52155. return Action;
  52156. }());
  52157. BABYLON.Action = Action;
  52158. })(BABYLON || (BABYLON = {}));
  52159. //# sourceMappingURL=babylon.action.js.map
  52160. var BABYLON;
  52161. (function (BABYLON) {
  52162. /**
  52163. * ActionEvent is the event being sent when an action is triggered.
  52164. */
  52165. var ActionEvent = /** @class */ (function () {
  52166. /**
  52167. * Creates a new ActionEvent
  52168. * @param source The mesh or sprite that triggered the action
  52169. * @param pointerX The X mouse cursor position at the time of the event
  52170. * @param pointerY The Y mouse cursor position at the time of the event
  52171. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52172. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52173. * @param additionalData additional data for the event
  52174. */
  52175. function ActionEvent(
  52176. /** The mesh or sprite that triggered the action */
  52177. source,
  52178. /** The X mouse cursor position at the time of the event */
  52179. pointerX,
  52180. /** The Y mouse cursor position at the time of the event */
  52181. pointerY,
  52182. /** The mesh that is currently pointed at (can be null) */
  52183. meshUnderPointer,
  52184. /** the original (browser) event that triggered the ActionEvent */
  52185. sourceEvent,
  52186. /** additional data for the event */
  52187. additionalData) {
  52188. this.source = source;
  52189. this.pointerX = pointerX;
  52190. this.pointerY = pointerY;
  52191. this.meshUnderPointer = meshUnderPointer;
  52192. this.sourceEvent = sourceEvent;
  52193. this.additionalData = additionalData;
  52194. }
  52195. /**
  52196. * Helper function to auto-create an ActionEvent from a source mesh.
  52197. * @param source The source mesh that triggered the event
  52198. * @param evt The original (browser) event
  52199. * @param additionalData additional data for the event
  52200. * @returns the new ActionEvent
  52201. */
  52202. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52203. var scene = source.getScene();
  52204. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52205. };
  52206. /**
  52207. * Helper function to auto-create an ActionEvent from a source sprite
  52208. * @param source The source sprite that triggered the event
  52209. * @param scene Scene associated with the sprite
  52210. * @param evt The original (browser) event
  52211. * @param additionalData additional data for the event
  52212. * @returns the new ActionEvent
  52213. */
  52214. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52215. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52216. };
  52217. /**
  52218. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52219. * @param scene the scene where the event occurred
  52220. * @param evt The original (browser) event
  52221. * @returns the new ActionEvent
  52222. */
  52223. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52224. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52225. };
  52226. /**
  52227. * Helper function to auto-create an ActionEvent from a primitive
  52228. * @param prim defines the target primitive
  52229. * @param pointerPos defines the pointer position
  52230. * @param evt The original (browser) event
  52231. * @param additionalData additional data for the event
  52232. * @returns the new ActionEvent
  52233. */
  52234. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52235. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52236. };
  52237. return ActionEvent;
  52238. }());
  52239. BABYLON.ActionEvent = ActionEvent;
  52240. /**
  52241. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52242. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52243. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52244. */
  52245. var ActionManager = /** @class */ (function () {
  52246. /**
  52247. * Creates a new action manager
  52248. * @param scene defines the hosting scene
  52249. */
  52250. function ActionManager(scene) {
  52251. // Members
  52252. /** Gets the list of actions */
  52253. this.actions = new Array();
  52254. /** Gets the cursor to use when hovering items */
  52255. this.hoverCursor = '';
  52256. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52257. scene.actionManagers.push(this);
  52258. }
  52259. Object.defineProperty(ActionManager, "NothingTrigger", {
  52260. /**
  52261. * Nothing
  52262. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52263. */
  52264. get: function () {
  52265. return ActionManager._NothingTrigger;
  52266. },
  52267. enumerable: true,
  52268. configurable: true
  52269. });
  52270. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52271. /**
  52272. * On pick
  52273. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52274. */
  52275. get: function () {
  52276. return ActionManager._OnPickTrigger;
  52277. },
  52278. enumerable: true,
  52279. configurable: true
  52280. });
  52281. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52282. /**
  52283. * On left pick
  52284. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52285. */
  52286. get: function () {
  52287. return ActionManager._OnLeftPickTrigger;
  52288. },
  52289. enumerable: true,
  52290. configurable: true
  52291. });
  52292. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52293. /**
  52294. * On right pick
  52295. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52296. */
  52297. get: function () {
  52298. return ActionManager._OnRightPickTrigger;
  52299. },
  52300. enumerable: true,
  52301. configurable: true
  52302. });
  52303. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52304. /**
  52305. * On center pick
  52306. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52307. */
  52308. get: function () {
  52309. return ActionManager._OnCenterPickTrigger;
  52310. },
  52311. enumerable: true,
  52312. configurable: true
  52313. });
  52314. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52315. /**
  52316. * On pick down
  52317. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52318. */
  52319. get: function () {
  52320. return ActionManager._OnPickDownTrigger;
  52321. },
  52322. enumerable: true,
  52323. configurable: true
  52324. });
  52325. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52326. /**
  52327. * On double pick
  52328. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52329. */
  52330. get: function () {
  52331. return ActionManager._OnDoublePickTrigger;
  52332. },
  52333. enumerable: true,
  52334. configurable: true
  52335. });
  52336. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52337. /**
  52338. * On pick up
  52339. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52340. */
  52341. get: function () {
  52342. return ActionManager._OnPickUpTrigger;
  52343. },
  52344. enumerable: true,
  52345. configurable: true
  52346. });
  52347. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52348. /**
  52349. * On pick out.
  52350. * This trigger will only be raised if you also declared a OnPickDown
  52351. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52352. */
  52353. get: function () {
  52354. return ActionManager._OnPickOutTrigger;
  52355. },
  52356. enumerable: true,
  52357. configurable: true
  52358. });
  52359. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52360. /**
  52361. * On long press
  52362. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52363. */
  52364. get: function () {
  52365. return ActionManager._OnLongPressTrigger;
  52366. },
  52367. enumerable: true,
  52368. configurable: true
  52369. });
  52370. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52371. /**
  52372. * On pointer over
  52373. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52374. */
  52375. get: function () {
  52376. return ActionManager._OnPointerOverTrigger;
  52377. },
  52378. enumerable: true,
  52379. configurable: true
  52380. });
  52381. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52382. /**
  52383. * On pointer out
  52384. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52385. */
  52386. get: function () {
  52387. return ActionManager._OnPointerOutTrigger;
  52388. },
  52389. enumerable: true,
  52390. configurable: true
  52391. });
  52392. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52393. /**
  52394. * On every frame
  52395. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52396. */
  52397. get: function () {
  52398. return ActionManager._OnEveryFrameTrigger;
  52399. },
  52400. enumerable: true,
  52401. configurable: true
  52402. });
  52403. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52404. /**
  52405. * On intersection enter
  52406. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52407. */
  52408. get: function () {
  52409. return ActionManager._OnIntersectionEnterTrigger;
  52410. },
  52411. enumerable: true,
  52412. configurable: true
  52413. });
  52414. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52415. /**
  52416. * On intersection exit
  52417. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52418. */
  52419. get: function () {
  52420. return ActionManager._OnIntersectionExitTrigger;
  52421. },
  52422. enumerable: true,
  52423. configurable: true
  52424. });
  52425. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52426. /**
  52427. * On key down
  52428. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52429. */
  52430. get: function () {
  52431. return ActionManager._OnKeyDownTrigger;
  52432. },
  52433. enumerable: true,
  52434. configurable: true
  52435. });
  52436. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52437. /**
  52438. * On key up
  52439. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52440. */
  52441. get: function () {
  52442. return ActionManager._OnKeyUpTrigger;
  52443. },
  52444. enumerable: true,
  52445. configurable: true
  52446. });
  52447. // Methods
  52448. /**
  52449. * Releases all associated resources
  52450. */
  52451. ActionManager.prototype.dispose = function () {
  52452. var index = this._scene.actionManagers.indexOf(this);
  52453. for (var i = 0; i < this.actions.length; i++) {
  52454. var action = this.actions[i];
  52455. ActionManager.Triggers[action.trigger]--;
  52456. if (ActionManager.Triggers[action.trigger] === 0) {
  52457. delete ActionManager.Triggers[action.trigger];
  52458. }
  52459. }
  52460. if (index > -1) {
  52461. this._scene.actionManagers.splice(index, 1);
  52462. }
  52463. };
  52464. /**
  52465. * Gets hosting scene
  52466. * @returns the hosting scene
  52467. */
  52468. ActionManager.prototype.getScene = function () {
  52469. return this._scene;
  52470. };
  52471. /**
  52472. * Does this action manager handles actions of any of the given triggers
  52473. * @param triggers defines the triggers to be tested
  52474. * @return a boolean indicating whether one (or more) of the triggers is handled
  52475. */
  52476. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52477. for (var index = 0; index < this.actions.length; index++) {
  52478. var action = this.actions[index];
  52479. if (triggers.indexOf(action.trigger) > -1) {
  52480. return true;
  52481. }
  52482. }
  52483. return false;
  52484. };
  52485. /**
  52486. * Does this action manager handles actions of a given trigger
  52487. * @param trigger defines the trigger to be tested
  52488. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52489. * @return whether the trigger is handled
  52490. */
  52491. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52492. for (var index = 0; index < this.actions.length; index++) {
  52493. var action = this.actions[index];
  52494. if (action.trigger === trigger) {
  52495. if (parameterPredicate) {
  52496. if (parameterPredicate(action.getTriggerParameter())) {
  52497. return true;
  52498. }
  52499. }
  52500. else {
  52501. return true;
  52502. }
  52503. }
  52504. }
  52505. return false;
  52506. };
  52507. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52508. /**
  52509. * Does this action manager has pointer triggers
  52510. */
  52511. get: function () {
  52512. for (var index = 0; index < this.actions.length; index++) {
  52513. var action = this.actions[index];
  52514. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52515. return true;
  52516. }
  52517. }
  52518. return false;
  52519. },
  52520. enumerable: true,
  52521. configurable: true
  52522. });
  52523. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52524. /**
  52525. * Does this action manager has pick triggers
  52526. */
  52527. get: function () {
  52528. for (var index = 0; index < this.actions.length; index++) {
  52529. var action = this.actions[index];
  52530. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52531. return true;
  52532. }
  52533. }
  52534. return false;
  52535. },
  52536. enumerable: true,
  52537. configurable: true
  52538. });
  52539. Object.defineProperty(ActionManager, "HasTriggers", {
  52540. /**
  52541. * Does exist one action manager with at least one trigger
  52542. **/
  52543. get: function () {
  52544. for (var t in ActionManager.Triggers) {
  52545. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52546. return true;
  52547. }
  52548. }
  52549. return false;
  52550. },
  52551. enumerable: true,
  52552. configurable: true
  52553. });
  52554. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52555. /**
  52556. * Does exist one action manager with at least one pick trigger
  52557. **/
  52558. get: function () {
  52559. for (var t in ActionManager.Triggers) {
  52560. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52561. var t_int = parseInt(t);
  52562. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52563. return true;
  52564. }
  52565. }
  52566. }
  52567. return false;
  52568. },
  52569. enumerable: true,
  52570. configurable: true
  52571. });
  52572. /**
  52573. * Does exist one action manager that handles actions of a given trigger
  52574. * @param trigger defines the trigger to be tested
  52575. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52576. **/
  52577. ActionManager.HasSpecificTrigger = function (trigger) {
  52578. for (var t in ActionManager.Triggers) {
  52579. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52580. var t_int = parseInt(t);
  52581. if (t_int === trigger) {
  52582. return true;
  52583. }
  52584. }
  52585. }
  52586. return false;
  52587. };
  52588. /**
  52589. * Registers an action to this action manager
  52590. * @param action defines the action to be registered
  52591. * @return the action amended (prepared) after registration
  52592. */
  52593. ActionManager.prototype.registerAction = function (action) {
  52594. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52595. if (this.getScene().actionManager !== this) {
  52596. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52597. return null;
  52598. }
  52599. }
  52600. this.actions.push(action);
  52601. if (ActionManager.Triggers[action.trigger]) {
  52602. ActionManager.Triggers[action.trigger]++;
  52603. }
  52604. else {
  52605. ActionManager.Triggers[action.trigger] = 1;
  52606. }
  52607. action._actionManager = this;
  52608. action._prepare();
  52609. return action;
  52610. };
  52611. /**
  52612. * Unregisters an action to this action manager
  52613. * @param action defines the action to be unregistered
  52614. * @return a boolean indicating whether the action has been unregistered
  52615. */
  52616. ActionManager.prototype.unregisterAction = function (action) {
  52617. var index = this.actions.indexOf(action);
  52618. if (index !== -1) {
  52619. this.actions.splice(index, 1);
  52620. ActionManager.Triggers[action.trigger] -= 1;
  52621. if (ActionManager.Triggers[action.trigger] === 0) {
  52622. delete ActionManager.Triggers[action.trigger];
  52623. }
  52624. delete action._actionManager;
  52625. return true;
  52626. }
  52627. return false;
  52628. };
  52629. /**
  52630. * Process a specific trigger
  52631. * @param trigger defines the trigger to process
  52632. * @param evt defines the event details to be processed
  52633. */
  52634. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52635. for (var index = 0; index < this.actions.length; index++) {
  52636. var action = this.actions[index];
  52637. if (action.trigger === trigger) {
  52638. if (evt) {
  52639. if (trigger === ActionManager.OnKeyUpTrigger
  52640. || trigger === ActionManager.OnKeyDownTrigger) {
  52641. var parameter = action.getTriggerParameter();
  52642. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52643. if (!parameter.toLowerCase) {
  52644. continue;
  52645. }
  52646. var lowerCase = parameter.toLowerCase();
  52647. if (lowerCase !== evt.sourceEvent.key) {
  52648. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52649. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52650. if (actualkey !== lowerCase) {
  52651. continue;
  52652. }
  52653. }
  52654. }
  52655. }
  52656. }
  52657. action._executeCurrent(evt);
  52658. }
  52659. }
  52660. };
  52661. /** @hidden */
  52662. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52663. var properties = propertyPath.split(".");
  52664. for (var index = 0; index < properties.length - 1; index++) {
  52665. target = target[properties[index]];
  52666. }
  52667. return target;
  52668. };
  52669. /** @hidden */
  52670. ActionManager.prototype._getProperty = function (propertyPath) {
  52671. var properties = propertyPath.split(".");
  52672. return properties[properties.length - 1];
  52673. };
  52674. /**
  52675. * Serialize this manager to a JSON object
  52676. * @param name defines the property name to store this manager
  52677. * @returns a JSON representation of this manager
  52678. */
  52679. ActionManager.prototype.serialize = function (name) {
  52680. var root = {
  52681. children: new Array(),
  52682. name: name,
  52683. type: 3,
  52684. properties: new Array() // Empty for root but required
  52685. };
  52686. for (var i = 0; i < this.actions.length; i++) {
  52687. var triggerObject = {
  52688. type: 0,
  52689. children: new Array(),
  52690. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52691. properties: new Array()
  52692. };
  52693. var triggerOptions = this.actions[i].triggerOptions;
  52694. if (triggerOptions && typeof triggerOptions !== "number") {
  52695. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52696. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52697. }
  52698. else {
  52699. var parameter = {};
  52700. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52701. if (triggerOptions.parameter.mesh) {
  52702. parameter._meshId = triggerOptions.parameter.mesh.id;
  52703. }
  52704. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52705. }
  52706. }
  52707. // Serialize child action, recursively
  52708. this.actions[i].serialize(triggerObject);
  52709. // Add serialized trigger
  52710. root.children.push(triggerObject);
  52711. }
  52712. return root;
  52713. };
  52714. /**
  52715. * Creates a new ActionManager from a JSON data
  52716. * @param parsedActions defines the JSON data to read from
  52717. * @param object defines the hosting mesh
  52718. * @param scene defines the hosting scene
  52719. */
  52720. ActionManager.Parse = function (parsedActions, object, scene) {
  52721. var actionManager = new ActionManager(scene);
  52722. if (object === null)
  52723. scene.actionManager = actionManager;
  52724. else
  52725. object.actionManager = actionManager;
  52726. // instanciate a new object
  52727. var instanciate = function (name, params) {
  52728. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52729. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52730. newInstance.constructor.apply(newInstance, params);
  52731. return newInstance;
  52732. };
  52733. var parseParameter = function (name, value, target, propertyPath) {
  52734. if (propertyPath === null) {
  52735. // String, boolean or float
  52736. var floatValue = parseFloat(value);
  52737. if (value === "true" || value === "false")
  52738. return value === "true";
  52739. else
  52740. return isNaN(floatValue) ? value : floatValue;
  52741. }
  52742. var effectiveTarget = propertyPath.split(".");
  52743. var values = value.split(",");
  52744. // Get effective Target
  52745. for (var i = 0; i < effectiveTarget.length; i++) {
  52746. target = target[effectiveTarget[i]];
  52747. }
  52748. // Return appropriate value with its type
  52749. if (typeof (target) === "boolean")
  52750. return values[0] === "true";
  52751. if (typeof (target) === "string")
  52752. return values[0];
  52753. // Parameters with multiple values such as Vector3 etc.
  52754. var split = new Array();
  52755. for (var i = 0; i < values.length; i++)
  52756. split.push(parseFloat(values[i]));
  52757. if (target instanceof BABYLON.Vector3)
  52758. return BABYLON.Vector3.FromArray(split);
  52759. if (target instanceof BABYLON.Vector4)
  52760. return BABYLON.Vector4.FromArray(split);
  52761. if (target instanceof BABYLON.Color3)
  52762. return BABYLON.Color3.FromArray(split);
  52763. if (target instanceof BABYLON.Color4)
  52764. return BABYLON.Color4.FromArray(split);
  52765. return parseFloat(values[0]);
  52766. };
  52767. // traverse graph per trigger
  52768. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52769. if (combineArray === void 0) { combineArray = null; }
  52770. if (parsedAction.detached)
  52771. return;
  52772. var parameters = new Array();
  52773. var target = null;
  52774. var propertyPath = null;
  52775. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52776. // Parameters
  52777. if (parsedAction.type === 2)
  52778. parameters.push(actionManager);
  52779. else
  52780. parameters.push(trigger);
  52781. if (combine) {
  52782. var actions = new Array();
  52783. for (var j = 0; j < parsedAction.combine.length; j++) {
  52784. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52785. }
  52786. parameters.push(actions);
  52787. }
  52788. else {
  52789. for (var i = 0; i < parsedAction.properties.length; i++) {
  52790. var value = parsedAction.properties[i].value;
  52791. var name = parsedAction.properties[i].name;
  52792. var targetType = parsedAction.properties[i].targetType;
  52793. if (name === "target")
  52794. if (targetType !== null && targetType === "SceneProperties")
  52795. value = target = scene;
  52796. else
  52797. value = target = scene.getNodeByName(value);
  52798. else if (name === "parent")
  52799. value = scene.getNodeByName(value);
  52800. else if (name === "sound")
  52801. value = scene.getSoundByName(value);
  52802. else if (name !== "propertyPath") {
  52803. if (parsedAction.type === 2 && name === "operator")
  52804. value = BABYLON.ValueCondition[value];
  52805. else
  52806. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52807. }
  52808. else {
  52809. propertyPath = value;
  52810. }
  52811. parameters.push(value);
  52812. }
  52813. }
  52814. if (combineArray === null) {
  52815. parameters.push(condition);
  52816. }
  52817. else {
  52818. parameters.push(null);
  52819. }
  52820. // If interpolate value action
  52821. if (parsedAction.name === "InterpolateValueAction") {
  52822. var param = parameters[parameters.length - 2];
  52823. parameters[parameters.length - 1] = param;
  52824. parameters[parameters.length - 2] = condition;
  52825. }
  52826. // Action or condition(s) and not CombineAction
  52827. var newAction = instanciate(parsedAction.name, parameters);
  52828. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52829. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52830. if (action)
  52831. action.then(nothing);
  52832. else
  52833. actionManager.registerAction(nothing);
  52834. action = nothing;
  52835. }
  52836. if (combineArray === null) {
  52837. if (newAction instanceof BABYLON.Condition) {
  52838. condition = newAction;
  52839. newAction = action;
  52840. }
  52841. else {
  52842. condition = null;
  52843. if (action)
  52844. action.then(newAction);
  52845. else
  52846. actionManager.registerAction(newAction);
  52847. }
  52848. }
  52849. else {
  52850. combineArray.push(newAction);
  52851. }
  52852. for (var i = 0; i < parsedAction.children.length; i++)
  52853. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52854. };
  52855. // triggers
  52856. for (var i = 0; i < parsedActions.children.length; i++) {
  52857. var triggerParams;
  52858. var trigger = parsedActions.children[i];
  52859. if (trigger.properties.length > 0) {
  52860. var param = trigger.properties[0].value;
  52861. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52862. if (value._meshId) {
  52863. value.mesh = scene.getMeshByID(value._meshId);
  52864. }
  52865. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52866. }
  52867. else
  52868. triggerParams = ActionManager[trigger.name];
  52869. for (var j = 0; j < trigger.children.length; j++) {
  52870. if (!trigger.detached)
  52871. traverse(trigger.children[j], triggerParams, null, null);
  52872. }
  52873. }
  52874. };
  52875. /**
  52876. * Get a trigger name by index
  52877. * @param trigger defines the trigger index
  52878. * @returns a trigger name
  52879. */
  52880. ActionManager.GetTriggerName = function (trigger) {
  52881. switch (trigger) {
  52882. case 0: return "NothingTrigger";
  52883. case 1: return "OnPickTrigger";
  52884. case 2: return "OnLeftPickTrigger";
  52885. case 3: return "OnRightPickTrigger";
  52886. case 4: return "OnCenterPickTrigger";
  52887. case 5: return "OnPickDownTrigger";
  52888. case 6: return "OnPickUpTrigger";
  52889. case 7: return "OnLongPressTrigger";
  52890. case 8: return "OnPointerOverTrigger";
  52891. case 9: return "OnPointerOutTrigger";
  52892. case 10: return "OnEveryFrameTrigger";
  52893. case 11: return "OnIntersectionEnterTrigger";
  52894. case 12: return "OnIntersectionExitTrigger";
  52895. case 13: return "OnKeyDownTrigger";
  52896. case 14: return "OnKeyUpTrigger";
  52897. case 15: return "OnPickOutTrigger";
  52898. default: return "";
  52899. }
  52900. };
  52901. // Statics
  52902. ActionManager._NothingTrigger = 0;
  52903. ActionManager._OnPickTrigger = 1;
  52904. ActionManager._OnLeftPickTrigger = 2;
  52905. ActionManager._OnRightPickTrigger = 3;
  52906. ActionManager._OnCenterPickTrigger = 4;
  52907. ActionManager._OnPickDownTrigger = 5;
  52908. ActionManager._OnDoublePickTrigger = 6;
  52909. ActionManager._OnPickUpTrigger = 7;
  52910. ActionManager._OnLongPressTrigger = 8;
  52911. ActionManager._OnPointerOverTrigger = 9;
  52912. ActionManager._OnPointerOutTrigger = 10;
  52913. ActionManager._OnEveryFrameTrigger = 11;
  52914. ActionManager._OnIntersectionEnterTrigger = 12;
  52915. ActionManager._OnIntersectionExitTrigger = 13;
  52916. ActionManager._OnKeyDownTrigger = 14;
  52917. ActionManager._OnKeyUpTrigger = 15;
  52918. ActionManager._OnPickOutTrigger = 16;
  52919. /** Gets the list of active triggers */
  52920. ActionManager.Triggers = {};
  52921. return ActionManager;
  52922. }());
  52923. BABYLON.ActionManager = ActionManager;
  52924. })(BABYLON || (BABYLON = {}));
  52925. //# sourceMappingURL=babylon.actionManager.js.map
  52926. var BABYLON;
  52927. (function (BABYLON) {
  52928. var InterpolateValueAction = /** @class */ (function (_super) {
  52929. __extends(InterpolateValueAction, _super);
  52930. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52931. if (duration === void 0) { duration = 1000; }
  52932. var _this = _super.call(this, triggerOptions, condition) || this;
  52933. _this.propertyPath = propertyPath;
  52934. _this.value = value;
  52935. _this.duration = duration;
  52936. _this.stopOtherAnimations = stopOtherAnimations;
  52937. _this.onInterpolationDone = onInterpolationDone;
  52938. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52939. _this._target = _this._effectiveTarget = target;
  52940. return _this;
  52941. }
  52942. InterpolateValueAction.prototype._prepare = function () {
  52943. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52944. this._property = this._getProperty(this.propertyPath);
  52945. };
  52946. InterpolateValueAction.prototype.execute = function () {
  52947. var _this = this;
  52948. var scene = this._actionManager.getScene();
  52949. var keys = [
  52950. {
  52951. frame: 0,
  52952. value: this._effectiveTarget[this._property]
  52953. }, {
  52954. frame: 100,
  52955. value: this.value
  52956. }
  52957. ];
  52958. var dataType;
  52959. if (typeof this.value === "number") {
  52960. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52961. }
  52962. else if (this.value instanceof BABYLON.Color3) {
  52963. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52964. }
  52965. else if (this.value instanceof BABYLON.Vector3) {
  52966. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52967. }
  52968. else if (this.value instanceof BABYLON.Matrix) {
  52969. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52970. }
  52971. else if (this.value instanceof BABYLON.Quaternion) {
  52972. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52973. }
  52974. else {
  52975. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52976. return;
  52977. }
  52978. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52979. animation.setKeys(keys);
  52980. if (this.stopOtherAnimations) {
  52981. scene.stopAnimation(this._effectiveTarget);
  52982. }
  52983. var wrapper = function () {
  52984. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52985. if (_this.onInterpolationDone) {
  52986. _this.onInterpolationDone();
  52987. }
  52988. };
  52989. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52990. };
  52991. InterpolateValueAction.prototype.serialize = function (parent) {
  52992. return _super.prototype._serialize.call(this, {
  52993. name: "InterpolateValueAction",
  52994. properties: [
  52995. BABYLON.Action._GetTargetProperty(this._target),
  52996. { name: "propertyPath", value: this.propertyPath },
  52997. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52998. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52999. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53000. ]
  53001. }, parent);
  53002. };
  53003. return InterpolateValueAction;
  53004. }(BABYLON.Action));
  53005. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53006. })(BABYLON || (BABYLON = {}));
  53007. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53008. var BABYLON;
  53009. (function (BABYLON) {
  53010. var SwitchBooleanAction = /** @class */ (function (_super) {
  53011. __extends(SwitchBooleanAction, _super);
  53012. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53013. var _this = _super.call(this, triggerOptions, condition) || this;
  53014. _this.propertyPath = propertyPath;
  53015. _this._target = _this._effectiveTarget = target;
  53016. return _this;
  53017. }
  53018. SwitchBooleanAction.prototype._prepare = function () {
  53019. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53020. this._property = this._getProperty(this.propertyPath);
  53021. };
  53022. SwitchBooleanAction.prototype.execute = function () {
  53023. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53024. };
  53025. SwitchBooleanAction.prototype.serialize = function (parent) {
  53026. return _super.prototype._serialize.call(this, {
  53027. name: "SwitchBooleanAction",
  53028. properties: [
  53029. BABYLON.Action._GetTargetProperty(this._target),
  53030. { name: "propertyPath", value: this.propertyPath }
  53031. ]
  53032. }, parent);
  53033. };
  53034. return SwitchBooleanAction;
  53035. }(BABYLON.Action));
  53036. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53037. var SetStateAction = /** @class */ (function (_super) {
  53038. __extends(SetStateAction, _super);
  53039. function SetStateAction(triggerOptions, target, value, condition) {
  53040. var _this = _super.call(this, triggerOptions, condition) || this;
  53041. _this.value = value;
  53042. _this._target = target;
  53043. return _this;
  53044. }
  53045. SetStateAction.prototype.execute = function () {
  53046. this._target.state = this.value;
  53047. };
  53048. SetStateAction.prototype.serialize = function (parent) {
  53049. return _super.prototype._serialize.call(this, {
  53050. name: "SetStateAction",
  53051. properties: [
  53052. BABYLON.Action._GetTargetProperty(this._target),
  53053. { name: "value", value: this.value }
  53054. ]
  53055. }, parent);
  53056. };
  53057. return SetStateAction;
  53058. }(BABYLON.Action));
  53059. BABYLON.SetStateAction = SetStateAction;
  53060. var SetValueAction = /** @class */ (function (_super) {
  53061. __extends(SetValueAction, _super);
  53062. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53063. var _this = _super.call(this, triggerOptions, condition) || this;
  53064. _this.propertyPath = propertyPath;
  53065. _this.value = value;
  53066. _this._target = _this._effectiveTarget = target;
  53067. return _this;
  53068. }
  53069. SetValueAction.prototype._prepare = function () {
  53070. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53071. this._property = this._getProperty(this.propertyPath);
  53072. };
  53073. SetValueAction.prototype.execute = function () {
  53074. this._effectiveTarget[this._property] = this.value;
  53075. if (this._target.markAsDirty) {
  53076. this._target.markAsDirty(this._property);
  53077. }
  53078. };
  53079. SetValueAction.prototype.serialize = function (parent) {
  53080. return _super.prototype._serialize.call(this, {
  53081. name: "SetValueAction",
  53082. properties: [
  53083. BABYLON.Action._GetTargetProperty(this._target),
  53084. { name: "propertyPath", value: this.propertyPath },
  53085. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53086. ]
  53087. }, parent);
  53088. };
  53089. return SetValueAction;
  53090. }(BABYLON.Action));
  53091. BABYLON.SetValueAction = SetValueAction;
  53092. var IncrementValueAction = /** @class */ (function (_super) {
  53093. __extends(IncrementValueAction, _super);
  53094. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53095. var _this = _super.call(this, triggerOptions, condition) || this;
  53096. _this.propertyPath = propertyPath;
  53097. _this.value = value;
  53098. _this._target = _this._effectiveTarget = target;
  53099. return _this;
  53100. }
  53101. IncrementValueAction.prototype._prepare = function () {
  53102. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53103. this._property = this._getProperty(this.propertyPath);
  53104. if (typeof this._effectiveTarget[this._property] !== "number") {
  53105. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53106. }
  53107. };
  53108. IncrementValueAction.prototype.execute = function () {
  53109. this._effectiveTarget[this._property] += this.value;
  53110. if (this._target.markAsDirty) {
  53111. this._target.markAsDirty(this._property);
  53112. }
  53113. };
  53114. IncrementValueAction.prototype.serialize = function (parent) {
  53115. return _super.prototype._serialize.call(this, {
  53116. name: "IncrementValueAction",
  53117. properties: [
  53118. BABYLON.Action._GetTargetProperty(this._target),
  53119. { name: "propertyPath", value: this.propertyPath },
  53120. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53121. ]
  53122. }, parent);
  53123. };
  53124. return IncrementValueAction;
  53125. }(BABYLON.Action));
  53126. BABYLON.IncrementValueAction = IncrementValueAction;
  53127. var PlayAnimationAction = /** @class */ (function (_super) {
  53128. __extends(PlayAnimationAction, _super);
  53129. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53130. var _this = _super.call(this, triggerOptions, condition) || this;
  53131. _this.from = from;
  53132. _this.to = to;
  53133. _this.loop = loop;
  53134. _this._target = target;
  53135. return _this;
  53136. }
  53137. PlayAnimationAction.prototype._prepare = function () {
  53138. };
  53139. PlayAnimationAction.prototype.execute = function () {
  53140. var scene = this._actionManager.getScene();
  53141. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53142. };
  53143. PlayAnimationAction.prototype.serialize = function (parent) {
  53144. return _super.prototype._serialize.call(this, {
  53145. name: "PlayAnimationAction",
  53146. properties: [
  53147. BABYLON.Action._GetTargetProperty(this._target),
  53148. { name: "from", value: String(this.from) },
  53149. { name: "to", value: String(this.to) },
  53150. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53151. ]
  53152. }, parent);
  53153. };
  53154. return PlayAnimationAction;
  53155. }(BABYLON.Action));
  53156. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53157. var StopAnimationAction = /** @class */ (function (_super) {
  53158. __extends(StopAnimationAction, _super);
  53159. function StopAnimationAction(triggerOptions, target, condition) {
  53160. var _this = _super.call(this, triggerOptions, condition) || this;
  53161. _this._target = target;
  53162. return _this;
  53163. }
  53164. StopAnimationAction.prototype._prepare = function () {
  53165. };
  53166. StopAnimationAction.prototype.execute = function () {
  53167. var scene = this._actionManager.getScene();
  53168. scene.stopAnimation(this._target);
  53169. };
  53170. StopAnimationAction.prototype.serialize = function (parent) {
  53171. return _super.prototype._serialize.call(this, {
  53172. name: "StopAnimationAction",
  53173. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53174. }, parent);
  53175. };
  53176. return StopAnimationAction;
  53177. }(BABYLON.Action));
  53178. BABYLON.StopAnimationAction = StopAnimationAction;
  53179. var DoNothingAction = /** @class */ (function (_super) {
  53180. __extends(DoNothingAction, _super);
  53181. function DoNothingAction(triggerOptions, condition) {
  53182. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53183. return _super.call(this, triggerOptions, condition) || this;
  53184. }
  53185. DoNothingAction.prototype.execute = function () {
  53186. };
  53187. DoNothingAction.prototype.serialize = function (parent) {
  53188. return _super.prototype._serialize.call(this, {
  53189. name: "DoNothingAction",
  53190. properties: []
  53191. }, parent);
  53192. };
  53193. return DoNothingAction;
  53194. }(BABYLON.Action));
  53195. BABYLON.DoNothingAction = DoNothingAction;
  53196. var CombineAction = /** @class */ (function (_super) {
  53197. __extends(CombineAction, _super);
  53198. function CombineAction(triggerOptions, children, condition) {
  53199. var _this = _super.call(this, triggerOptions, condition) || this;
  53200. _this.children = children;
  53201. return _this;
  53202. }
  53203. CombineAction.prototype._prepare = function () {
  53204. for (var index = 0; index < this.children.length; index++) {
  53205. this.children[index]._actionManager = this._actionManager;
  53206. this.children[index]._prepare();
  53207. }
  53208. };
  53209. CombineAction.prototype.execute = function (evt) {
  53210. for (var index = 0; index < this.children.length; index++) {
  53211. this.children[index].execute(evt);
  53212. }
  53213. };
  53214. CombineAction.prototype.serialize = function (parent) {
  53215. var serializationObject = _super.prototype._serialize.call(this, {
  53216. name: "CombineAction",
  53217. properties: [],
  53218. combine: []
  53219. }, parent);
  53220. for (var i = 0; i < this.children.length; i++) {
  53221. serializationObject.combine.push(this.children[i].serialize(null));
  53222. }
  53223. return serializationObject;
  53224. };
  53225. return CombineAction;
  53226. }(BABYLON.Action));
  53227. BABYLON.CombineAction = CombineAction;
  53228. var ExecuteCodeAction = /** @class */ (function (_super) {
  53229. __extends(ExecuteCodeAction, _super);
  53230. function ExecuteCodeAction(triggerOptions, func, condition) {
  53231. var _this = _super.call(this, triggerOptions, condition) || this;
  53232. _this.func = func;
  53233. return _this;
  53234. }
  53235. ExecuteCodeAction.prototype.execute = function (evt) {
  53236. this.func(evt);
  53237. };
  53238. return ExecuteCodeAction;
  53239. }(BABYLON.Action));
  53240. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53241. var SetParentAction = /** @class */ (function (_super) {
  53242. __extends(SetParentAction, _super);
  53243. function SetParentAction(triggerOptions, target, parent, condition) {
  53244. var _this = _super.call(this, triggerOptions, condition) || this;
  53245. _this._target = target;
  53246. _this._parent = parent;
  53247. return _this;
  53248. }
  53249. SetParentAction.prototype._prepare = function () {
  53250. };
  53251. SetParentAction.prototype.execute = function () {
  53252. if (this._target.parent === this._parent) {
  53253. return;
  53254. }
  53255. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53256. invertParentWorldMatrix.invert();
  53257. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53258. this._target.parent = this._parent;
  53259. };
  53260. SetParentAction.prototype.serialize = function (parent) {
  53261. return _super.prototype._serialize.call(this, {
  53262. name: "SetParentAction",
  53263. properties: [
  53264. BABYLON.Action._GetTargetProperty(this._target),
  53265. BABYLON.Action._GetTargetProperty(this._parent),
  53266. ]
  53267. }, parent);
  53268. };
  53269. return SetParentAction;
  53270. }(BABYLON.Action));
  53271. BABYLON.SetParentAction = SetParentAction;
  53272. var PlaySoundAction = /** @class */ (function (_super) {
  53273. __extends(PlaySoundAction, _super);
  53274. function PlaySoundAction(triggerOptions, sound, condition) {
  53275. var _this = _super.call(this, triggerOptions, condition) || this;
  53276. _this._sound = sound;
  53277. return _this;
  53278. }
  53279. PlaySoundAction.prototype._prepare = function () {
  53280. };
  53281. PlaySoundAction.prototype.execute = function () {
  53282. if (this._sound !== undefined)
  53283. this._sound.play();
  53284. };
  53285. PlaySoundAction.prototype.serialize = function (parent) {
  53286. return _super.prototype._serialize.call(this, {
  53287. name: "PlaySoundAction",
  53288. properties: [{ name: "sound", value: this._sound.name }]
  53289. }, parent);
  53290. };
  53291. return PlaySoundAction;
  53292. }(BABYLON.Action));
  53293. BABYLON.PlaySoundAction = PlaySoundAction;
  53294. var StopSoundAction = /** @class */ (function (_super) {
  53295. __extends(StopSoundAction, _super);
  53296. function StopSoundAction(triggerOptions, sound, condition) {
  53297. var _this = _super.call(this, triggerOptions, condition) || this;
  53298. _this._sound = sound;
  53299. return _this;
  53300. }
  53301. StopSoundAction.prototype._prepare = function () {
  53302. };
  53303. StopSoundAction.prototype.execute = function () {
  53304. if (this._sound !== undefined)
  53305. this._sound.stop();
  53306. };
  53307. StopSoundAction.prototype.serialize = function (parent) {
  53308. return _super.prototype._serialize.call(this, {
  53309. name: "StopSoundAction",
  53310. properties: [{ name: "sound", value: this._sound.name }]
  53311. }, parent);
  53312. };
  53313. return StopSoundAction;
  53314. }(BABYLON.Action));
  53315. BABYLON.StopSoundAction = StopSoundAction;
  53316. })(BABYLON || (BABYLON = {}));
  53317. //# sourceMappingURL=babylon.directActions.js.map
  53318. var BABYLON;
  53319. (function (BABYLON) {
  53320. var SpriteManager = /** @class */ (function () {
  53321. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53322. if (epsilon === void 0) { epsilon = 0.01; }
  53323. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53324. this.name = name;
  53325. this.sprites = new Array();
  53326. this.renderingGroupId = 0;
  53327. this.layerMask = 0x0FFFFFFF;
  53328. this.fogEnabled = true;
  53329. this.isPickable = false;
  53330. /**
  53331. * An event triggered when the manager is disposed.
  53332. */
  53333. this.onDisposeObservable = new BABYLON.Observable();
  53334. this._vertexBuffers = {};
  53335. this._capacity = capacity;
  53336. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53337. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53338. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53339. if (cellSize.width && cellSize.height) {
  53340. this.cellWidth = cellSize.width;
  53341. this.cellHeight = cellSize.height;
  53342. }
  53343. else if (cellSize !== undefined) {
  53344. this.cellWidth = cellSize;
  53345. this.cellHeight = cellSize;
  53346. }
  53347. else {
  53348. return;
  53349. }
  53350. this._epsilon = epsilon;
  53351. this._scene = scene;
  53352. this._scene.spriteManagers.push(this);
  53353. var indices = [];
  53354. var index = 0;
  53355. for (var count = 0; count < capacity; count++) {
  53356. indices.push(index);
  53357. indices.push(index + 1);
  53358. indices.push(index + 2);
  53359. indices.push(index);
  53360. indices.push(index + 2);
  53361. indices.push(index + 3);
  53362. index += 4;
  53363. }
  53364. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53365. // VBO
  53366. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53367. this._vertexData = new Float32Array(capacity * 16 * 4);
  53368. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53369. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53370. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53371. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53372. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53373. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53374. this._vertexBuffers["options"] = options;
  53375. this._vertexBuffers["cellInfo"] = cellInfo;
  53376. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53377. // Effects
  53378. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53379. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53380. }
  53381. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53382. set: function (callback) {
  53383. if (this._onDisposeObserver) {
  53384. this.onDisposeObservable.remove(this._onDisposeObserver);
  53385. }
  53386. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53387. },
  53388. enumerable: true,
  53389. configurable: true
  53390. });
  53391. Object.defineProperty(SpriteManager.prototype, "texture", {
  53392. get: function () {
  53393. return this._spriteTexture;
  53394. },
  53395. set: function (value) {
  53396. this._spriteTexture = value;
  53397. },
  53398. enumerable: true,
  53399. configurable: true
  53400. });
  53401. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53402. var arrayOffset = index * 16;
  53403. if (offsetX === 0)
  53404. offsetX = this._epsilon;
  53405. else if (offsetX === 1)
  53406. offsetX = 1 - this._epsilon;
  53407. if (offsetY === 0)
  53408. offsetY = this._epsilon;
  53409. else if (offsetY === 1)
  53410. offsetY = 1 - this._epsilon;
  53411. this._vertexData[arrayOffset] = sprite.position.x;
  53412. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53413. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53414. this._vertexData[arrayOffset + 3] = sprite.angle;
  53415. this._vertexData[arrayOffset + 4] = sprite.width;
  53416. this._vertexData[arrayOffset + 5] = sprite.height;
  53417. this._vertexData[arrayOffset + 6] = offsetX;
  53418. this._vertexData[arrayOffset + 7] = offsetY;
  53419. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53420. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53421. var offset = (sprite.cellIndex / rowSize) >> 0;
  53422. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53423. this._vertexData[arrayOffset + 11] = offset;
  53424. // Color
  53425. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53426. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53427. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53428. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53429. };
  53430. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53431. var count = Math.min(this._capacity, this.sprites.length);
  53432. var min = BABYLON.Vector3.Zero();
  53433. var max = BABYLON.Vector3.Zero();
  53434. var distance = Number.MAX_VALUE;
  53435. var currentSprite = null;
  53436. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53437. var cameraView = camera.getViewMatrix();
  53438. for (var index = 0; index < count; index++) {
  53439. var sprite = this.sprites[index];
  53440. if (!sprite) {
  53441. continue;
  53442. }
  53443. if (predicate) {
  53444. if (!predicate(sprite)) {
  53445. continue;
  53446. }
  53447. }
  53448. else if (!sprite.isPickable) {
  53449. continue;
  53450. }
  53451. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53452. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53453. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53454. if (ray.intersectsBoxMinMax(min, max)) {
  53455. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53456. if (distance > currentDistance) {
  53457. distance = currentDistance;
  53458. currentSprite = sprite;
  53459. if (fastCheck) {
  53460. break;
  53461. }
  53462. }
  53463. }
  53464. }
  53465. if (currentSprite) {
  53466. var result = new BABYLON.PickingInfo();
  53467. result.hit = true;
  53468. result.pickedSprite = currentSprite;
  53469. result.distance = distance;
  53470. return result;
  53471. }
  53472. return null;
  53473. };
  53474. SpriteManager.prototype.render = function () {
  53475. // Check
  53476. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53477. return;
  53478. var engine = this._scene.getEngine();
  53479. var baseSize = this._spriteTexture.getBaseSize();
  53480. // Sprites
  53481. var deltaTime = engine.getDeltaTime();
  53482. var max = Math.min(this._capacity, this.sprites.length);
  53483. var rowSize = baseSize.width / this.cellWidth;
  53484. var offset = 0;
  53485. for (var index = 0; index < max; index++) {
  53486. var sprite = this.sprites[index];
  53487. if (!sprite || !sprite.isVisible) {
  53488. continue;
  53489. }
  53490. sprite._animate(deltaTime);
  53491. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53492. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53493. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53494. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53495. }
  53496. this._buffer.update(this._vertexData);
  53497. // Render
  53498. var effect = this._effectBase;
  53499. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53500. effect = this._effectFog;
  53501. }
  53502. engine.enableEffect(effect);
  53503. var viewMatrix = this._scene.getViewMatrix();
  53504. effect.setTexture("diffuseSampler", this._spriteTexture);
  53505. effect.setMatrix("view", viewMatrix);
  53506. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53507. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53508. // Fog
  53509. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53510. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53511. effect.setColor3("vFogColor", this._scene.fogColor);
  53512. }
  53513. // VBOs
  53514. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53515. // Draw order
  53516. engine.setDepthFunctionToLessOrEqual();
  53517. effect.setBool("alphaTest", true);
  53518. engine.setColorWrite(false);
  53519. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53520. engine.setColorWrite(true);
  53521. effect.setBool("alphaTest", false);
  53522. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53523. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53524. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53525. };
  53526. SpriteManager.prototype.dispose = function () {
  53527. if (this._buffer) {
  53528. this._buffer.dispose();
  53529. this._buffer = null;
  53530. }
  53531. if (this._indexBuffer) {
  53532. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53533. this._indexBuffer = null;
  53534. }
  53535. if (this._spriteTexture) {
  53536. this._spriteTexture.dispose();
  53537. this._spriteTexture = null;
  53538. }
  53539. // Remove from scene
  53540. var index = this._scene.spriteManagers.indexOf(this);
  53541. this._scene.spriteManagers.splice(index, 1);
  53542. // Callback
  53543. this.onDisposeObservable.notifyObservers(this);
  53544. this.onDisposeObservable.clear();
  53545. };
  53546. return SpriteManager;
  53547. }());
  53548. BABYLON.SpriteManager = SpriteManager;
  53549. })(BABYLON || (BABYLON = {}));
  53550. //# sourceMappingURL=babylon.spriteManager.js.map
  53551. var BABYLON;
  53552. (function (BABYLON) {
  53553. var Sprite = /** @class */ (function () {
  53554. function Sprite(name, manager) {
  53555. this.name = name;
  53556. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53557. this.width = 1.0;
  53558. this.height = 1.0;
  53559. this.angle = 0;
  53560. this.cellIndex = 0;
  53561. this.invertU = 0;
  53562. this.invertV = 0;
  53563. this.animations = new Array();
  53564. this.isPickable = false;
  53565. this._animationStarted = false;
  53566. this._loopAnimation = false;
  53567. this._fromIndex = 0;
  53568. this._toIndex = 0;
  53569. this._delay = 0;
  53570. this._direction = 1;
  53571. this._time = 0;
  53572. /**
  53573. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53574. */
  53575. this.isVisible = true;
  53576. this._manager = manager;
  53577. this._manager.sprites.push(this);
  53578. this.position = BABYLON.Vector3.Zero();
  53579. }
  53580. Object.defineProperty(Sprite.prototype, "size", {
  53581. get: function () {
  53582. return this.width;
  53583. },
  53584. set: function (value) {
  53585. this.width = value;
  53586. this.height = value;
  53587. },
  53588. enumerable: true,
  53589. configurable: true
  53590. });
  53591. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53592. this._fromIndex = from;
  53593. this._toIndex = to;
  53594. this._loopAnimation = loop;
  53595. this._delay = delay;
  53596. this._animationStarted = true;
  53597. this._direction = from < to ? 1 : -1;
  53598. this.cellIndex = from;
  53599. this._time = 0;
  53600. this._onAnimationEnd = onAnimationEnd;
  53601. };
  53602. Sprite.prototype.stopAnimation = function () {
  53603. this._animationStarted = false;
  53604. };
  53605. Sprite.prototype._animate = function (deltaTime) {
  53606. if (!this._animationStarted)
  53607. return;
  53608. this._time += deltaTime;
  53609. if (this._time > this._delay) {
  53610. this._time = this._time % this._delay;
  53611. this.cellIndex += this._direction;
  53612. if (this.cellIndex > this._toIndex) {
  53613. if (this._loopAnimation) {
  53614. this.cellIndex = this._fromIndex;
  53615. }
  53616. else {
  53617. this.cellIndex = this._toIndex;
  53618. this._animationStarted = false;
  53619. if (this._onAnimationEnd) {
  53620. this._onAnimationEnd();
  53621. }
  53622. if (this.disposeWhenFinishedAnimating) {
  53623. this.dispose();
  53624. }
  53625. }
  53626. }
  53627. }
  53628. };
  53629. Sprite.prototype.dispose = function () {
  53630. for (var i = 0; i < this._manager.sprites.length; i++) {
  53631. if (this._manager.sprites[i] == this) {
  53632. this._manager.sprites.splice(i, 1);
  53633. }
  53634. }
  53635. };
  53636. return Sprite;
  53637. }());
  53638. BABYLON.Sprite = Sprite;
  53639. })(BABYLON || (BABYLON = {}));
  53640. //# sourceMappingURL=babylon.sprite.js.map
  53641. var BABYLON;
  53642. (function (BABYLON) {
  53643. var IntersectionInfo = /** @class */ (function () {
  53644. function IntersectionInfo(bu, bv, distance) {
  53645. this.bu = bu;
  53646. this.bv = bv;
  53647. this.distance = distance;
  53648. this.faceId = 0;
  53649. this.subMeshId = 0;
  53650. }
  53651. return IntersectionInfo;
  53652. }());
  53653. BABYLON.IntersectionInfo = IntersectionInfo;
  53654. /**
  53655. * Information about the result of picking within a scene
  53656. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53657. */
  53658. var PickingInfo = /** @class */ (function () {
  53659. function PickingInfo() {
  53660. /**
  53661. * If the pick collided with an object
  53662. */
  53663. this.hit = false;
  53664. /**
  53665. * Distance away where the pick collided
  53666. */
  53667. this.distance = 0;
  53668. /**
  53669. * The location of pick collision
  53670. */
  53671. this.pickedPoint = null;
  53672. /**
  53673. * The mesh corrisponding the the pick collision
  53674. */
  53675. this.pickedMesh = null;
  53676. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53677. this.bu = 0;
  53678. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53679. this.bv = 0;
  53680. /** The id of the face on the mesh that was picked */
  53681. this.faceId = -1;
  53682. /** Id of the the submesh that was picked */
  53683. this.subMeshId = 0;
  53684. /** If a sprite was picked, this will be the sprite the pick collided with */
  53685. this.pickedSprite = null;
  53686. /**
  53687. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53688. */
  53689. this.originMesh = null;
  53690. /**
  53691. * The ray that was used to perform the picking.
  53692. */
  53693. this.ray = null;
  53694. }
  53695. /**
  53696. * Gets the normal corrispodning to the face the pick collided with
  53697. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53698. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53699. * @returns The normal corrispodning to the face the pick collided with
  53700. */
  53701. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53702. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53703. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53704. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53705. return null;
  53706. }
  53707. var indices = this.pickedMesh.getIndices();
  53708. if (!indices) {
  53709. return null;
  53710. }
  53711. var result;
  53712. if (useVerticesNormals) {
  53713. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53714. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53715. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53716. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53717. normal0 = normal0.scale(this.bu);
  53718. normal1 = normal1.scale(this.bv);
  53719. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53720. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53721. }
  53722. else {
  53723. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53724. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53725. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53726. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53727. var p1p2 = vertex1.subtract(vertex2);
  53728. var p3p2 = vertex3.subtract(vertex2);
  53729. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53730. }
  53731. if (useWorldCoordinates) {
  53732. var wm = this.pickedMesh.getWorldMatrix();
  53733. if (this.pickedMesh.nonUniformScaling) {
  53734. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53735. wm = BABYLON.Tmp.Matrix[0];
  53736. wm.setTranslationFromFloats(0, 0, 0);
  53737. wm.invert();
  53738. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53739. wm = BABYLON.Tmp.Matrix[1];
  53740. }
  53741. result = BABYLON.Vector3.TransformNormal(result, wm);
  53742. }
  53743. result.normalize();
  53744. return result;
  53745. };
  53746. /**
  53747. * Gets the texture coordinates of where the pick occured
  53748. * @returns the vector containing the coordnates of the texture
  53749. */
  53750. PickingInfo.prototype.getTextureCoordinates = function () {
  53751. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53752. return null;
  53753. }
  53754. var indices = this.pickedMesh.getIndices();
  53755. if (!indices) {
  53756. return null;
  53757. }
  53758. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53759. if (!uvs) {
  53760. return null;
  53761. }
  53762. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53763. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53764. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53765. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53766. uv1 = uv1.scale(this.bu);
  53767. uv2 = uv2.scale(this.bv);
  53768. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53769. };
  53770. return PickingInfo;
  53771. }());
  53772. BABYLON.PickingInfo = PickingInfo;
  53773. })(BABYLON || (BABYLON = {}));
  53774. //# sourceMappingURL=babylon.pickingInfo.js.map
  53775. var BABYLON;
  53776. (function (BABYLON) {
  53777. var Ray = /** @class */ (function () {
  53778. function Ray(origin, direction, length) {
  53779. if (length === void 0) { length = Number.MAX_VALUE; }
  53780. this.origin = origin;
  53781. this.direction = direction;
  53782. this.length = length;
  53783. }
  53784. // Methods
  53785. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53786. var d = 0.0;
  53787. var maxValue = Number.MAX_VALUE;
  53788. var inv;
  53789. var min;
  53790. var max;
  53791. var temp;
  53792. if (Math.abs(this.direction.x) < 0.0000001) {
  53793. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53794. return false;
  53795. }
  53796. }
  53797. else {
  53798. inv = 1.0 / this.direction.x;
  53799. min = (minimum.x - this.origin.x) * inv;
  53800. max = (maximum.x - this.origin.x) * inv;
  53801. if (max === -Infinity) {
  53802. max = Infinity;
  53803. }
  53804. if (min > max) {
  53805. temp = min;
  53806. min = max;
  53807. max = temp;
  53808. }
  53809. d = Math.max(min, d);
  53810. maxValue = Math.min(max, maxValue);
  53811. if (d > maxValue) {
  53812. return false;
  53813. }
  53814. }
  53815. if (Math.abs(this.direction.y) < 0.0000001) {
  53816. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53817. return false;
  53818. }
  53819. }
  53820. else {
  53821. inv = 1.0 / this.direction.y;
  53822. min = (minimum.y - this.origin.y) * inv;
  53823. max = (maximum.y - this.origin.y) * inv;
  53824. if (max === -Infinity) {
  53825. max = Infinity;
  53826. }
  53827. if (min > max) {
  53828. temp = min;
  53829. min = max;
  53830. max = temp;
  53831. }
  53832. d = Math.max(min, d);
  53833. maxValue = Math.min(max, maxValue);
  53834. if (d > maxValue) {
  53835. return false;
  53836. }
  53837. }
  53838. if (Math.abs(this.direction.z) < 0.0000001) {
  53839. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53840. return false;
  53841. }
  53842. }
  53843. else {
  53844. inv = 1.0 / this.direction.z;
  53845. min = (minimum.z - this.origin.z) * inv;
  53846. max = (maximum.z - this.origin.z) * inv;
  53847. if (max === -Infinity) {
  53848. max = Infinity;
  53849. }
  53850. if (min > max) {
  53851. temp = min;
  53852. min = max;
  53853. max = temp;
  53854. }
  53855. d = Math.max(min, d);
  53856. maxValue = Math.min(max, maxValue);
  53857. if (d > maxValue) {
  53858. return false;
  53859. }
  53860. }
  53861. return true;
  53862. };
  53863. Ray.prototype.intersectsBox = function (box) {
  53864. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53865. };
  53866. Ray.prototype.intersectsSphere = function (sphere) {
  53867. var x = sphere.center.x - this.origin.x;
  53868. var y = sphere.center.y - this.origin.y;
  53869. var z = sphere.center.z - this.origin.z;
  53870. var pyth = (x * x) + (y * y) + (z * z);
  53871. var rr = sphere.radius * sphere.radius;
  53872. if (pyth <= rr) {
  53873. return true;
  53874. }
  53875. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53876. if (dot < 0.0) {
  53877. return false;
  53878. }
  53879. var temp = pyth - (dot * dot);
  53880. return temp <= rr;
  53881. };
  53882. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53883. if (!this._edge1) {
  53884. this._edge1 = BABYLON.Vector3.Zero();
  53885. this._edge2 = BABYLON.Vector3.Zero();
  53886. this._pvec = BABYLON.Vector3.Zero();
  53887. this._tvec = BABYLON.Vector3.Zero();
  53888. this._qvec = BABYLON.Vector3.Zero();
  53889. }
  53890. vertex1.subtractToRef(vertex0, this._edge1);
  53891. vertex2.subtractToRef(vertex0, this._edge2);
  53892. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53893. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53894. if (det === 0) {
  53895. return null;
  53896. }
  53897. var invdet = 1 / det;
  53898. this.origin.subtractToRef(vertex0, this._tvec);
  53899. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53900. if (bu < 0 || bu > 1.0) {
  53901. return null;
  53902. }
  53903. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53904. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53905. if (bv < 0 || bu + bv > 1.0) {
  53906. return null;
  53907. }
  53908. //check if the distance is longer than the predefined length.
  53909. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53910. if (distance > this.length) {
  53911. return null;
  53912. }
  53913. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53914. };
  53915. Ray.prototype.intersectsPlane = function (plane) {
  53916. var distance;
  53917. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53918. if (Math.abs(result1) < 9.99999997475243E-07) {
  53919. return null;
  53920. }
  53921. else {
  53922. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53923. distance = (-plane.d - result2) / result1;
  53924. if (distance < 0.0) {
  53925. if (distance < -9.99999997475243E-07) {
  53926. return null;
  53927. }
  53928. else {
  53929. return 0;
  53930. }
  53931. }
  53932. return distance;
  53933. }
  53934. };
  53935. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53936. var tm = BABYLON.Tmp.Matrix[0];
  53937. mesh.getWorldMatrix().invertToRef(tm);
  53938. if (this._tmpRay) {
  53939. Ray.TransformToRef(this, tm, this._tmpRay);
  53940. }
  53941. else {
  53942. this._tmpRay = Ray.Transform(this, tm);
  53943. }
  53944. return mesh.intersects(this._tmpRay, fastCheck);
  53945. };
  53946. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53947. if (results) {
  53948. results.length = 0;
  53949. }
  53950. else {
  53951. results = [];
  53952. }
  53953. for (var i = 0; i < meshes.length; i++) {
  53954. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53955. if (pickInfo.hit) {
  53956. results.push(pickInfo);
  53957. }
  53958. }
  53959. results.sort(this._comparePickingInfo);
  53960. return results;
  53961. };
  53962. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53963. if (pickingInfoA.distance < pickingInfoB.distance) {
  53964. return -1;
  53965. }
  53966. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53967. return 1;
  53968. }
  53969. else {
  53970. return 0;
  53971. }
  53972. };
  53973. /**
  53974. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53975. * @param sega the first point of the segment to test the intersection against
  53976. * @param segb the second point of the segment to test the intersection against
  53977. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53978. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53979. */
  53980. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53981. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53982. var u = segb.subtract(sega);
  53983. var v = rsegb.subtract(this.origin);
  53984. var w = sega.subtract(this.origin);
  53985. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53986. var b = BABYLON.Vector3.Dot(u, v);
  53987. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53988. var d = BABYLON.Vector3.Dot(u, w);
  53989. var e = BABYLON.Vector3.Dot(v, w);
  53990. var D = a * c - b * b; // always >= 0
  53991. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53992. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53993. // compute the line parameters of the two closest points
  53994. if (D < Ray.smallnum) { // the lines are almost parallel
  53995. sN = 0.0; // force using point P0 on segment S1
  53996. sD = 1.0; // to prevent possible division by 0.0 later
  53997. tN = e;
  53998. tD = c;
  53999. }
  54000. else { // get the closest points on the infinite lines
  54001. sN = (b * e - c * d);
  54002. tN = (a * e - b * d);
  54003. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54004. sN = 0.0;
  54005. tN = e;
  54006. tD = c;
  54007. }
  54008. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54009. sN = sD;
  54010. tN = e + b;
  54011. tD = c;
  54012. }
  54013. }
  54014. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54015. tN = 0.0;
  54016. // recompute sc for this edge
  54017. if (-d < 0.0) {
  54018. sN = 0.0;
  54019. }
  54020. else if (-d > a)
  54021. sN = sD;
  54022. else {
  54023. sN = -d;
  54024. sD = a;
  54025. }
  54026. }
  54027. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54028. tN = tD;
  54029. // recompute sc for this edge
  54030. if ((-d + b) < 0.0) {
  54031. sN = 0;
  54032. }
  54033. else if ((-d + b) > a) {
  54034. sN = sD;
  54035. }
  54036. else {
  54037. sN = (-d + b);
  54038. sD = a;
  54039. }
  54040. }
  54041. // finally do the division to get sc and tc
  54042. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54043. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54044. // get the difference of the two closest points
  54045. var qtc = v.multiplyByFloats(tc, tc, tc);
  54046. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54047. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54048. if (isIntersected) {
  54049. return qtc.length();
  54050. }
  54051. return -1;
  54052. };
  54053. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54054. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54055. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54056. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54057. this.direction.normalize();
  54058. return this;
  54059. };
  54060. // Statics
  54061. Ray.Zero = function () {
  54062. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54063. };
  54064. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54065. var result = Ray.Zero();
  54066. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54067. };
  54068. /**
  54069. * 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
  54070. * transformed to the given world matrix.
  54071. * @param origin The origin point
  54072. * @param end The end point
  54073. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54074. */
  54075. Ray.CreateNewFromTo = function (origin, end, world) {
  54076. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54077. var direction = end.subtract(origin);
  54078. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54079. direction.normalize();
  54080. return Ray.Transform(new Ray(origin, direction, length), world);
  54081. };
  54082. Ray.Transform = function (ray, matrix) {
  54083. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54084. Ray.TransformToRef(ray, matrix, result);
  54085. return result;
  54086. };
  54087. Ray.TransformToRef = function (ray, matrix, result) {
  54088. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54089. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54090. result.length = ray.length;
  54091. var dir = result.direction;
  54092. var len = dir.length();
  54093. if (!(len === 0 || len === 1)) {
  54094. var num = 1.0 / len;
  54095. dir.x *= num;
  54096. dir.y *= num;
  54097. dir.z *= num;
  54098. result.length *= len;
  54099. }
  54100. };
  54101. Ray.smallnum = 0.00000001;
  54102. Ray.rayl = 10e8;
  54103. return Ray;
  54104. }());
  54105. BABYLON.Ray = Ray;
  54106. })(BABYLON || (BABYLON = {}));
  54107. //# sourceMappingURL=babylon.ray.js.map
  54108. var BABYLON;
  54109. (function (BABYLON) {
  54110. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54111. if (boxMin.x > sphereCenter.x + sphereRadius)
  54112. return false;
  54113. if (sphereCenter.x - sphereRadius > boxMax.x)
  54114. return false;
  54115. if (boxMin.y > sphereCenter.y + sphereRadius)
  54116. return false;
  54117. if (sphereCenter.y - sphereRadius > boxMax.y)
  54118. return false;
  54119. if (boxMin.z > sphereCenter.z + sphereRadius)
  54120. return false;
  54121. if (sphereCenter.z - sphereRadius > boxMax.z)
  54122. return false;
  54123. return true;
  54124. };
  54125. var getLowestRoot = (function () {
  54126. var result = { root: 0, found: false };
  54127. return function (a, b, c, maxR) {
  54128. result.root = 0;
  54129. result.found = false;
  54130. var determinant = b * b - 4.0 * a * c;
  54131. if (determinant < 0)
  54132. return result;
  54133. var sqrtD = Math.sqrt(determinant);
  54134. var r1 = (-b - sqrtD) / (2.0 * a);
  54135. var r2 = (-b + sqrtD) / (2.0 * a);
  54136. if (r1 > r2) {
  54137. var temp = r2;
  54138. r2 = r1;
  54139. r1 = temp;
  54140. }
  54141. if (r1 > 0 && r1 < maxR) {
  54142. result.root = r1;
  54143. result.found = true;
  54144. return result;
  54145. }
  54146. if (r2 > 0 && r2 < maxR) {
  54147. result.root = r2;
  54148. result.found = true;
  54149. return result;
  54150. }
  54151. return result;
  54152. };
  54153. })();
  54154. var Collider = /** @class */ (function () {
  54155. function Collider() {
  54156. this._collisionPoint = BABYLON.Vector3.Zero();
  54157. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54158. this._tempVector = BABYLON.Vector3.Zero();
  54159. this._tempVector2 = BABYLON.Vector3.Zero();
  54160. this._tempVector3 = BABYLON.Vector3.Zero();
  54161. this._tempVector4 = BABYLON.Vector3.Zero();
  54162. this._edge = BABYLON.Vector3.Zero();
  54163. this._baseToVertex = BABYLON.Vector3.Zero();
  54164. this._destinationPoint = BABYLON.Vector3.Zero();
  54165. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54166. this._displacementVector = BABYLON.Vector3.Zero();
  54167. this._radius = BABYLON.Vector3.One();
  54168. this._retry = 0;
  54169. this._basePointWorld = BABYLON.Vector3.Zero();
  54170. this._velocityWorld = BABYLON.Vector3.Zero();
  54171. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54172. this._collisionMask = -1;
  54173. }
  54174. Object.defineProperty(Collider.prototype, "collisionMask", {
  54175. get: function () {
  54176. return this._collisionMask;
  54177. },
  54178. set: function (mask) {
  54179. this._collisionMask = !isNaN(mask) ? mask : -1;
  54180. },
  54181. enumerable: true,
  54182. configurable: true
  54183. });
  54184. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54185. /**
  54186. * Gets the plane normal used to compute the sliding response (in local space)
  54187. */
  54188. get: function () {
  54189. return this._slidePlaneNormal;
  54190. },
  54191. enumerable: true,
  54192. configurable: true
  54193. });
  54194. // Methods
  54195. Collider.prototype._initialize = function (source, dir, e) {
  54196. this._velocity = dir;
  54197. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54198. this._basePoint = source;
  54199. source.multiplyToRef(this._radius, this._basePointWorld);
  54200. dir.multiplyToRef(this._radius, this._velocityWorld);
  54201. this._velocityWorldLength = this._velocityWorld.length();
  54202. this._epsilon = e;
  54203. this.collisionFound = false;
  54204. };
  54205. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54206. pa.subtractToRef(point, this._tempVector);
  54207. pb.subtractToRef(point, this._tempVector2);
  54208. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54209. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54210. if (d < 0)
  54211. return false;
  54212. pc.subtractToRef(point, this._tempVector3);
  54213. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54214. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54215. if (d < 0)
  54216. return false;
  54217. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54218. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54219. return d >= 0;
  54220. };
  54221. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54222. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54223. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54224. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54225. return false;
  54226. }
  54227. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54228. return false;
  54229. return true;
  54230. };
  54231. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54232. var t0;
  54233. var embeddedInPlane = false;
  54234. //defensive programming, actually not needed.
  54235. if (!trianglePlaneArray) {
  54236. trianglePlaneArray = [];
  54237. }
  54238. if (!trianglePlaneArray[faceIndex]) {
  54239. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54240. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54241. }
  54242. var trianglePlane = trianglePlaneArray[faceIndex];
  54243. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54244. return;
  54245. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54246. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54247. if (normalDotVelocity == 0) {
  54248. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54249. return;
  54250. embeddedInPlane = true;
  54251. t0 = 0;
  54252. }
  54253. else {
  54254. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54255. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54256. if (t0 > t1) {
  54257. var temp = t1;
  54258. t1 = t0;
  54259. t0 = temp;
  54260. }
  54261. if (t0 > 1.0 || t1 < 0.0)
  54262. return;
  54263. if (t0 < 0)
  54264. t0 = 0;
  54265. if (t0 > 1.0)
  54266. t0 = 1.0;
  54267. }
  54268. this._collisionPoint.copyFromFloats(0, 0, 0);
  54269. var found = false;
  54270. var t = 1.0;
  54271. if (!embeddedInPlane) {
  54272. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54273. this._velocity.scaleToRef(t0, this._tempVector);
  54274. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54275. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54276. found = true;
  54277. t = t0;
  54278. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54279. }
  54280. }
  54281. if (!found) {
  54282. var velocitySquaredLength = this._velocity.lengthSquared();
  54283. var a = velocitySquaredLength;
  54284. this._basePoint.subtractToRef(p1, this._tempVector);
  54285. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54286. var c = this._tempVector.lengthSquared() - 1.0;
  54287. var lowestRoot = getLowestRoot(a, b, c, t);
  54288. if (lowestRoot.found) {
  54289. t = lowestRoot.root;
  54290. found = true;
  54291. this._collisionPoint.copyFrom(p1);
  54292. }
  54293. this._basePoint.subtractToRef(p2, this._tempVector);
  54294. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54295. c = this._tempVector.lengthSquared() - 1.0;
  54296. lowestRoot = getLowestRoot(a, b, c, t);
  54297. if (lowestRoot.found) {
  54298. t = lowestRoot.root;
  54299. found = true;
  54300. this._collisionPoint.copyFrom(p2);
  54301. }
  54302. this._basePoint.subtractToRef(p3, this._tempVector);
  54303. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54304. c = this._tempVector.lengthSquared() - 1.0;
  54305. lowestRoot = getLowestRoot(a, b, c, t);
  54306. if (lowestRoot.found) {
  54307. t = lowestRoot.root;
  54308. found = true;
  54309. this._collisionPoint.copyFrom(p3);
  54310. }
  54311. p2.subtractToRef(p1, this._edge);
  54312. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54313. var edgeSquaredLength = this._edge.lengthSquared();
  54314. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54315. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54316. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54317. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54318. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54319. lowestRoot = getLowestRoot(a, b, c, t);
  54320. if (lowestRoot.found) {
  54321. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54322. if (f >= 0.0 && f <= 1.0) {
  54323. t = lowestRoot.root;
  54324. found = true;
  54325. this._edge.scaleInPlace(f);
  54326. p1.addToRef(this._edge, this._collisionPoint);
  54327. }
  54328. }
  54329. p3.subtractToRef(p2, this._edge);
  54330. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54331. edgeSquaredLength = this._edge.lengthSquared();
  54332. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54333. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54334. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54335. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54336. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54337. lowestRoot = getLowestRoot(a, b, c, t);
  54338. if (lowestRoot.found) {
  54339. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54340. if (f >= 0.0 && f <= 1.0) {
  54341. t = lowestRoot.root;
  54342. found = true;
  54343. this._edge.scaleInPlace(f);
  54344. p2.addToRef(this._edge, this._collisionPoint);
  54345. }
  54346. }
  54347. p1.subtractToRef(p3, this._edge);
  54348. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54349. edgeSquaredLength = this._edge.lengthSquared();
  54350. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54351. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54352. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54353. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54354. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54355. lowestRoot = getLowestRoot(a, b, c, t);
  54356. if (lowestRoot.found) {
  54357. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54358. if (f >= 0.0 && f <= 1.0) {
  54359. t = lowestRoot.root;
  54360. found = true;
  54361. this._edge.scaleInPlace(f);
  54362. p3.addToRef(this._edge, this._collisionPoint);
  54363. }
  54364. }
  54365. }
  54366. if (found) {
  54367. var distToCollision = t * this._velocity.length();
  54368. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54369. if (!this.intersectionPoint) {
  54370. this.intersectionPoint = this._collisionPoint.clone();
  54371. }
  54372. else {
  54373. this.intersectionPoint.copyFrom(this._collisionPoint);
  54374. }
  54375. this._nearestDistance = distToCollision;
  54376. this.collisionFound = true;
  54377. }
  54378. }
  54379. };
  54380. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54381. for (var i = indexStart; i < indexEnd; i += 3) {
  54382. var p1 = pts[indices[i] - decal];
  54383. var p2 = pts[indices[i + 1] - decal];
  54384. var p3 = pts[indices[i + 2] - decal];
  54385. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54386. }
  54387. };
  54388. Collider.prototype._getResponse = function (pos, vel) {
  54389. pos.addToRef(vel, this._destinationPoint);
  54390. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54391. this._basePoint.addToRef(vel, pos);
  54392. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54393. this._slidePlaneNormal.normalize();
  54394. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54395. pos.addInPlace(this._displacementVector);
  54396. this.intersectionPoint.addInPlace(this._displacementVector);
  54397. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54398. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54399. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54400. };
  54401. return Collider;
  54402. }());
  54403. BABYLON.Collider = Collider;
  54404. })(BABYLON || (BABYLON = {}));
  54405. //# sourceMappingURL=babylon.collider.js.map
  54406. var BABYLON;
  54407. (function (BABYLON) {
  54408. //WebWorker code will be inserted to this variable.
  54409. BABYLON.CollisionWorker = "";
  54410. /** Defines supported task for worker process */
  54411. var WorkerTaskType;
  54412. (function (WorkerTaskType) {
  54413. /** Initialization */
  54414. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54415. /** Update of geometry */
  54416. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54417. /** Evaluate collision */
  54418. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54419. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54420. /** Defines kind of replies returned by worker */
  54421. var WorkerReplyType;
  54422. (function (WorkerReplyType) {
  54423. /** Success */
  54424. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54425. /** Unkown error */
  54426. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54427. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54428. var CollisionCoordinatorWorker = /** @class */ (function () {
  54429. function CollisionCoordinatorWorker() {
  54430. var _this = this;
  54431. this._scaledPosition = BABYLON.Vector3.Zero();
  54432. this._scaledVelocity = BABYLON.Vector3.Zero();
  54433. this.onMeshUpdated = function (transformNode) {
  54434. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54435. };
  54436. this.onGeometryUpdated = function (geometry) {
  54437. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54438. };
  54439. this._afterRender = function () {
  54440. if (!_this._init)
  54441. return;
  54442. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54443. return;
  54444. }
  54445. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54446. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54447. if (_this._runningUpdated > 4) {
  54448. return;
  54449. }
  54450. ++_this._runningUpdated;
  54451. var payload = {
  54452. updatedMeshes: _this._addUpdateMeshesList,
  54453. updatedGeometries: _this._addUpdateGeometriesList,
  54454. removedGeometries: _this._toRemoveGeometryArray,
  54455. removedMeshes: _this._toRemoveMeshesArray
  54456. };
  54457. var message = {
  54458. payload: payload,
  54459. taskType: WorkerTaskType.UPDATE
  54460. };
  54461. var serializable = [];
  54462. for (var id in payload.updatedGeometries) {
  54463. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54464. //prepare transferables
  54465. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54466. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54467. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54468. }
  54469. }
  54470. _this._worker.postMessage(message, serializable);
  54471. _this._addUpdateMeshesList = {};
  54472. _this._addUpdateGeometriesList = {};
  54473. _this._toRemoveGeometryArray = [];
  54474. _this._toRemoveMeshesArray = [];
  54475. };
  54476. this._onMessageFromWorker = function (e) {
  54477. var returnData = e.data;
  54478. if (returnData.error != WorkerReplyType.SUCCESS) {
  54479. //TODO what errors can be returned from the worker?
  54480. BABYLON.Tools.Warn("error returned from worker!");
  54481. return;
  54482. }
  54483. switch (returnData.taskType) {
  54484. case WorkerTaskType.INIT:
  54485. _this._init = true;
  54486. //Update the worked with ALL of the scene's current state
  54487. _this._scene.meshes.forEach(function (mesh) {
  54488. _this.onMeshAdded(mesh);
  54489. });
  54490. _this._scene.getGeometries().forEach(function (geometry) {
  54491. _this.onGeometryAdded(geometry);
  54492. });
  54493. break;
  54494. case WorkerTaskType.UPDATE:
  54495. _this._runningUpdated--;
  54496. break;
  54497. case WorkerTaskType.COLLIDE:
  54498. var returnPayload = returnData.payload;
  54499. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54500. return;
  54501. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54502. if (callback) {
  54503. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54504. if (mesh) {
  54505. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54506. }
  54507. }
  54508. //cleanup
  54509. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54510. break;
  54511. }
  54512. };
  54513. this._collisionsCallbackArray = [];
  54514. this._init = false;
  54515. this._runningUpdated = 0;
  54516. this._addUpdateMeshesList = {};
  54517. this._addUpdateGeometriesList = {};
  54518. this._toRemoveGeometryArray = [];
  54519. this._toRemoveMeshesArray = [];
  54520. }
  54521. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54522. if (!this._init)
  54523. return;
  54524. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54525. return;
  54526. position.divideToRef(collider._radius, this._scaledPosition);
  54527. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54528. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54529. var payload = {
  54530. collider: {
  54531. position: this._scaledPosition.asArray(),
  54532. velocity: this._scaledVelocity.asArray(),
  54533. radius: collider._radius.asArray()
  54534. },
  54535. collisionId: collisionIndex,
  54536. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54537. maximumRetry: maximumRetry
  54538. };
  54539. var message = {
  54540. payload: payload,
  54541. taskType: WorkerTaskType.COLLIDE
  54542. };
  54543. this._worker.postMessage(message);
  54544. };
  54545. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54546. this._scene = scene;
  54547. this._scene.registerAfterRender(this._afterRender);
  54548. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54549. this._worker = new Worker(workerUrl);
  54550. this._worker.onmessage = this._onMessageFromWorker;
  54551. var message = {
  54552. payload: {},
  54553. taskType: WorkerTaskType.INIT
  54554. };
  54555. this._worker.postMessage(message);
  54556. };
  54557. CollisionCoordinatorWorker.prototype.destroy = function () {
  54558. this._scene.unregisterAfterRender(this._afterRender);
  54559. this._worker.terminate();
  54560. };
  54561. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54562. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54563. this.onMeshUpdated(mesh);
  54564. };
  54565. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54566. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54567. };
  54568. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54569. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54570. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54571. this.onGeometryUpdated(geometry);
  54572. };
  54573. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54574. this._toRemoveGeometryArray.push(geometry.id);
  54575. };
  54576. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54577. var submeshes = [];
  54578. if (mesh.subMeshes) {
  54579. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54580. var boundingInfo = sm.getBoundingInfo();
  54581. return {
  54582. position: idx,
  54583. verticesStart: sm.verticesStart,
  54584. verticesCount: sm.verticesCount,
  54585. indexStart: sm.indexStart,
  54586. indexCount: sm.indexCount,
  54587. hasMaterial: !!sm.getMaterial(),
  54588. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54589. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54590. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54591. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54592. };
  54593. });
  54594. }
  54595. var geometryId = null;
  54596. if (mesh instanceof BABYLON.Mesh) {
  54597. var geometry = mesh.geometry;
  54598. geometryId = geometry ? geometry.id : null;
  54599. }
  54600. else if (mesh instanceof BABYLON.InstancedMesh) {
  54601. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54602. geometryId = geometry ? geometry.id : null;
  54603. }
  54604. var boundingInfo = mesh.getBoundingInfo();
  54605. return {
  54606. uniqueId: mesh.uniqueId,
  54607. id: mesh.id,
  54608. name: mesh.name,
  54609. geometryId: geometryId,
  54610. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54611. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54612. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54613. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54614. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54615. subMeshes: submeshes,
  54616. checkCollisions: mesh.checkCollisions
  54617. };
  54618. };
  54619. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54620. return {
  54621. id: geometry.id,
  54622. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54623. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54624. indices: new Uint32Array(geometry.getIndices() || []),
  54625. };
  54626. };
  54627. return CollisionCoordinatorWorker;
  54628. }());
  54629. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54630. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54631. function CollisionCoordinatorLegacy() {
  54632. this._scaledPosition = BABYLON.Vector3.Zero();
  54633. this._scaledVelocity = BABYLON.Vector3.Zero();
  54634. this._finalPosition = BABYLON.Vector3.Zero();
  54635. }
  54636. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54637. position.divideToRef(collider._radius, this._scaledPosition);
  54638. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54639. collider.collidedMesh = null;
  54640. collider._retry = 0;
  54641. collider._initialVelocity = this._scaledVelocity;
  54642. collider._initialPosition = this._scaledPosition;
  54643. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54644. this._finalPosition.multiplyInPlace(collider._radius);
  54645. //run the callback
  54646. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54647. };
  54648. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54649. this._scene = scene;
  54650. };
  54651. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54652. //Legacy need no destruction method.
  54653. };
  54654. //No update in legacy mode
  54655. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54656. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54657. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54658. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54659. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54660. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54661. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54662. if (excludedMesh === void 0) { excludedMesh = null; }
  54663. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54664. if (collider._retry >= maximumRetry) {
  54665. finalPosition.copyFrom(position);
  54666. return;
  54667. }
  54668. // Check if this is a mesh else camera or -1
  54669. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54670. collider._initialize(position, velocity, closeDistance);
  54671. // Check all meshes
  54672. for (var index = 0; index < this._scene.meshes.length; index++) {
  54673. var mesh = this._scene.meshes[index];
  54674. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54675. mesh._checkCollision(collider);
  54676. }
  54677. }
  54678. if (!collider.collisionFound) {
  54679. position.addToRef(velocity, finalPosition);
  54680. return;
  54681. }
  54682. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54683. collider._getResponse(position, velocity);
  54684. }
  54685. if (velocity.length() <= closeDistance) {
  54686. finalPosition.copyFrom(position);
  54687. return;
  54688. }
  54689. collider._retry++;
  54690. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54691. };
  54692. return CollisionCoordinatorLegacy;
  54693. }());
  54694. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54695. })(BABYLON || (BABYLON = {}));
  54696. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54697. var BABYLON;
  54698. (function (BABYLON) {
  54699. /**
  54700. * A particle represents one of the element emitted by a particle system.
  54701. * This is mainly define by its coordinates, direction, velocity and age.
  54702. */
  54703. var Particle = /** @class */ (function () {
  54704. /**
  54705. * Creates a new instance Particle
  54706. * @param particleSystem the particle system the particle belongs to
  54707. */
  54708. function Particle(
  54709. /**
  54710. * particleSystem the particle system the particle belongs to.
  54711. */
  54712. particleSystem) {
  54713. this.particleSystem = particleSystem;
  54714. /**
  54715. * The world position of the particle in the scene.
  54716. */
  54717. this.position = BABYLON.Vector3.Zero();
  54718. /**
  54719. * The world direction of the particle in the scene.
  54720. */
  54721. this.direction = BABYLON.Vector3.Zero();
  54722. /**
  54723. * The color of the particle.
  54724. */
  54725. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54726. /**
  54727. * The color change of the particle per step.
  54728. */
  54729. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54730. /**
  54731. * Defines how long will the life of the particle be.
  54732. */
  54733. this.lifeTime = 1.0;
  54734. /**
  54735. * The current age of the particle.
  54736. */
  54737. this.age = 0;
  54738. /**
  54739. * The current size of the particle.
  54740. */
  54741. this.size = 0;
  54742. /**
  54743. * The current scale of the particle.
  54744. */
  54745. this.scale = new BABYLON.Vector2(1, 1);
  54746. /**
  54747. * The current angle of the particle.
  54748. */
  54749. this.angle = 0;
  54750. /**
  54751. * Defines how fast is the angle changing.
  54752. */
  54753. this.angularSpeed = 0;
  54754. /**
  54755. * Defines the cell index used by the particle to be rendered from a sprite.
  54756. */
  54757. this.cellIndex = 0;
  54758. /** @hidden */
  54759. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54760. /** @hidden */
  54761. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54762. /** @hidden */
  54763. this._currentSize1 = 0;
  54764. /** @hidden */
  54765. this._currentSize2 = 0;
  54766. /** @hidden */
  54767. this._currentAngularSpeed1 = 0;
  54768. /** @hidden */
  54769. this._currentAngularSpeed2 = 0;
  54770. /** @hidden */
  54771. this._currentVelocity1 = 0;
  54772. /** @hidden */
  54773. this._currentVelocity2 = 0;
  54774. if (!this.particleSystem.isAnimationSheetEnabled) {
  54775. return;
  54776. }
  54777. this.updateCellInfoFromSystem();
  54778. }
  54779. Particle.prototype.updateCellInfoFromSystem = function () {
  54780. this.cellIndex = this.particleSystem.startSpriteCellID;
  54781. };
  54782. /**
  54783. * Defines how the sprite cell index is updated for the particle
  54784. */
  54785. Particle.prototype.updateCellIndex = function () {
  54786. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54787. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54788. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54789. };
  54790. /**
  54791. * Copy the properties of particle to another one.
  54792. * @param other the particle to copy the information to.
  54793. */
  54794. Particle.prototype.copyTo = function (other) {
  54795. other.position.copyFrom(this.position);
  54796. if (this._initialDirection) {
  54797. if (other._initialDirection) {
  54798. other._initialDirection.copyFrom(this._initialDirection);
  54799. }
  54800. else {
  54801. other._initialDirection = this._initialDirection.clone();
  54802. }
  54803. }
  54804. else {
  54805. other._initialDirection = null;
  54806. }
  54807. other.direction.copyFrom(this.direction);
  54808. other.color.copyFrom(this.color);
  54809. other.colorStep.copyFrom(this.colorStep);
  54810. other.lifeTime = this.lifeTime;
  54811. other.age = this.age;
  54812. other.size = this.size;
  54813. other.scale.copyFrom(this.scale);
  54814. other.angle = this.angle;
  54815. other.angularSpeed = this.angularSpeed;
  54816. other.particleSystem = this.particleSystem;
  54817. other.cellIndex = this.cellIndex;
  54818. if (this._currentColorGradient) {
  54819. other._currentColorGradient = this._currentColorGradient;
  54820. other._currentColor1.copyFrom(this._currentColor1);
  54821. other._currentColor2.copyFrom(this._currentColor2);
  54822. }
  54823. if (this._currentSizeGradient) {
  54824. other._currentSizeGradient = this._currentSizeGradient;
  54825. other._currentSize1 = this._currentSize1;
  54826. other._currentSize2 = this._currentSize2;
  54827. }
  54828. if (this._currentAngularSpeedGradient) {
  54829. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54830. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54831. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54832. }
  54833. if (this._currentVelocityGradient) {
  54834. other._currentVelocityGradient = this._currentVelocityGradient;
  54835. other._currentVelocity1 = this._currentVelocity1;
  54836. other._currentVelocity2 = this._currentVelocity2;
  54837. }
  54838. if (this.particleSystem.isAnimationSheetEnabled) {
  54839. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54840. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54841. }
  54842. };
  54843. return Particle;
  54844. }());
  54845. BABYLON.Particle = Particle;
  54846. })(BABYLON || (BABYLON = {}));
  54847. //# sourceMappingURL=babylon.particle.js.map
  54848. var BABYLON;
  54849. (function (BABYLON) {
  54850. /**
  54851. * This represents a particle system in Babylon.
  54852. * 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.
  54853. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54854. * @example https://doc.babylonjs.com/babylon101/particles
  54855. */
  54856. var ParticleSystem = /** @class */ (function () {
  54857. /**
  54858. * Instantiates a particle system.
  54859. * 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.
  54860. * @param name The name of the particle system
  54861. * @param capacity The max number of particles alive at the same time
  54862. * @param scene The scene the particle system belongs to
  54863. * @param customEffect a custom effect used to change the way particles are rendered by default
  54864. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54865. * @param epsilon Offset used to render the particles
  54866. */
  54867. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54868. if (customEffect === void 0) { customEffect = null; }
  54869. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54870. if (epsilon === void 0) { epsilon = 0.01; }
  54871. var _this = this;
  54872. /**
  54873. * List of animations used by the particle system.
  54874. */
  54875. this.animations = [];
  54876. /**
  54877. * The rendering group used by the Particle system to chose when to render.
  54878. */
  54879. this.renderingGroupId = 0;
  54880. /**
  54881. * The emitter represents the Mesh or position we are attaching the particle system to.
  54882. */
  54883. this.emitter = null;
  54884. /**
  54885. * The maximum number of particles to emit per frame
  54886. */
  54887. this.emitRate = 10;
  54888. /**
  54889. * If you want to launch only a few particles at once, that can be done, as well.
  54890. */
  54891. this.manualEmitCount = -1;
  54892. /**
  54893. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54894. */
  54895. this.updateSpeed = 0.01;
  54896. /**
  54897. * The amount of time the particle system is running (depends of the overall update speed).
  54898. */
  54899. this.targetStopDuration = 0;
  54900. /**
  54901. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54902. */
  54903. this.disposeOnStop = false;
  54904. /**
  54905. * Minimum power of emitting particles.
  54906. */
  54907. this.minEmitPower = 1;
  54908. /**
  54909. * Maximum power of emitting particles.
  54910. */
  54911. this.maxEmitPower = 1;
  54912. /**
  54913. * Minimum life time of emitting particles.
  54914. */
  54915. this.minLifeTime = 1;
  54916. /**
  54917. * Maximum life time of emitting particles.
  54918. */
  54919. this.maxLifeTime = 1;
  54920. /**
  54921. * Minimum Size of emitting particles.
  54922. */
  54923. this.minSize = 1;
  54924. /**
  54925. * Maximum Size of emitting particles.
  54926. */
  54927. this.maxSize = 1;
  54928. /**
  54929. * Minimum scale of emitting particles on X axis.
  54930. */
  54931. this.minScaleX = 1;
  54932. /**
  54933. * Maximum scale of emitting particles on X axis.
  54934. */
  54935. this.maxScaleX = 1;
  54936. /**
  54937. * Minimum scale of emitting particles on Y axis.
  54938. */
  54939. this.minScaleY = 1;
  54940. /**
  54941. * Maximum scale of emitting particles on Y axis.
  54942. */
  54943. this.maxScaleY = 1;
  54944. /**
  54945. * Gets or sets the minimal initial rotation in radians.
  54946. */
  54947. this.minInitialRotation = 0;
  54948. /**
  54949. * Gets or sets the maximal initial rotation in radians.
  54950. */
  54951. this.maxInitialRotation = 0;
  54952. /**
  54953. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54954. */
  54955. this.minAngularSpeed = 0;
  54956. /**
  54957. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54958. */
  54959. this.maxAngularSpeed = 0;
  54960. /**
  54961. * The layer mask we are rendering the particles through.
  54962. */
  54963. this.layerMask = 0x0FFFFFFF;
  54964. /**
  54965. * This can help using your own shader to render the particle system.
  54966. * The according effect will be created
  54967. */
  54968. this.customShader = null;
  54969. /**
  54970. * By default particle system starts as soon as they are created. This prevents the
  54971. * automatic start to happen and let you decide when to start emitting particles.
  54972. */
  54973. this.preventAutoStart = false;
  54974. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  54975. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  54976. /**
  54977. * Callback triggered when the particle animation is ending.
  54978. */
  54979. this.onAnimationEnd = null;
  54980. /**
  54981. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54982. */
  54983. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54984. /**
  54985. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54986. * to override the particles.
  54987. */
  54988. this.forceDepthWrite = false;
  54989. /**
  54990. * You can use gravity if you want to give an orientation to your particles.
  54991. */
  54992. this.gravity = BABYLON.Vector3.Zero();
  54993. this._colorGradients = null;
  54994. this._sizeGradients = null;
  54995. this._lifeTimeGradients = null;
  54996. this._angularSpeedGradients = null;
  54997. this._velocityGradients = null;
  54998. /**
  54999. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55000. */
  55001. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55002. /**
  55003. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55004. */
  55005. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55006. /**
  55007. * Color the particle will have at the end of its lifetime
  55008. */
  55009. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55010. /**
  55011. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55012. */
  55013. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55014. /**
  55015. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55016. */
  55017. this.spriteCellChangeSpeed = 1;
  55018. /**
  55019. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55020. */
  55021. this.startSpriteCellID = 0;
  55022. /**
  55023. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55024. */
  55025. this.endSpriteCellID = 0;
  55026. /**
  55027. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55028. */
  55029. this.spriteCellWidth = 0;
  55030. /**
  55031. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55032. */
  55033. this.spriteCellHeight = 0;
  55034. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55035. this.preWarmCycles = 0;
  55036. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55037. this.preWarmStepOffset = 1;
  55038. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55039. this.translationPivot = new BABYLON.Vector2(0, 0);
  55040. /**
  55041. * An event triggered when the system is disposed
  55042. */
  55043. this.onDisposeObservable = new BABYLON.Observable();
  55044. /**
  55045. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55046. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55047. */
  55048. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55049. this._particles = new Array();
  55050. this._stockParticles = new Array();
  55051. this._newPartsExcess = 0;
  55052. this._vertexBuffers = {};
  55053. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55054. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55055. this._scaledDirection = BABYLON.Vector3.Zero();
  55056. this._scaledGravity = BABYLON.Vector3.Zero();
  55057. this._currentRenderId = -1;
  55058. this._useInstancing = false;
  55059. this._started = false;
  55060. this._stopped = false;
  55061. this._actualFrame = 0;
  55062. this._isBillboardBased = true;
  55063. // start of sub system methods
  55064. /**
  55065. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55066. * Its lifetime will start back at 0.
  55067. */
  55068. this.recycleParticle = function (particle) {
  55069. var lastParticle = _this._particles.pop();
  55070. if (lastParticle !== particle) {
  55071. lastParticle.copyTo(particle);
  55072. }
  55073. _this._stockParticles.push(lastParticle);
  55074. };
  55075. this._createParticle = function () {
  55076. var particle;
  55077. if (_this._stockParticles.length !== 0) {
  55078. particle = _this._stockParticles.pop();
  55079. particle.age = 0;
  55080. particle._currentColorGradient = null;
  55081. particle.cellIndex = _this.startSpriteCellID;
  55082. }
  55083. else {
  55084. particle = new BABYLON.Particle(_this);
  55085. }
  55086. return particle;
  55087. };
  55088. this._emitFromParticle = function (particle) {
  55089. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55090. return;
  55091. }
  55092. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55093. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55094. subSystem._rootParticleSystem = _this;
  55095. _this.activeSubSystems.push(subSystem);
  55096. subSystem.start();
  55097. };
  55098. this.id = name;
  55099. this.name = name;
  55100. this._capacity = capacity;
  55101. this._epsilon = epsilon;
  55102. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55103. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55104. this._customEffect = customEffect;
  55105. scene.particleSystems.push(this);
  55106. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55107. this._createIndexBuffer();
  55108. this._createVertexBuffers();
  55109. // Default emitter type
  55110. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55111. this.updateFunction = function (particles) {
  55112. var noiseTextureData = null;
  55113. var noiseTextureSize = null;
  55114. if (_this.noiseTexture) { // We need to get texture data back to CPU
  55115. noiseTextureData = (_this.noiseTexture.readPixels());
  55116. noiseTextureSize = _this.noiseTexture.getSize();
  55117. }
  55118. var _loop_1 = function () {
  55119. particle = particles[index];
  55120. particle.age += _this._scaledUpdateSpeed;
  55121. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55122. _this._emitFromParticle(particle);
  55123. _this.recycleParticle(particle);
  55124. index--;
  55125. return "continue";
  55126. }
  55127. else {
  55128. var ratio = particle.age / particle.lifeTime;
  55129. // Color
  55130. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55131. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55132. if (currentGradient !== particle._currentColorGradient) {
  55133. particle._currentColor1.copyFrom(particle._currentColor2);
  55134. nextGradient.getColorToRef(particle._currentColor2);
  55135. particle._currentColorGradient = currentGradient;
  55136. }
  55137. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55138. });
  55139. }
  55140. else {
  55141. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55142. particle.color.addInPlace(_this._scaledColorStep);
  55143. if (particle.color.a < 0) {
  55144. particle.color.a = 0;
  55145. }
  55146. }
  55147. // Angular speed
  55148. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55149. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55150. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55151. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55152. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55153. particle._currentAngularSpeedGradient = currentGradient;
  55154. }
  55155. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55156. });
  55157. }
  55158. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55159. // Direction
  55160. var directionScale_1 = _this._scaledUpdateSpeed;
  55161. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55162. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55163. if (currentGradient !== particle._currentVelocityGradient) {
  55164. particle._currentVelocity1 = particle._currentVelocity2;
  55165. particle._currentVelocity2 = nextGradient.getFactor();
  55166. particle._currentVelocityGradient = currentGradient;
  55167. }
  55168. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55169. });
  55170. }
  55171. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55172. particle.position.addInPlace(_this._scaledDirection);
  55173. // Noise
  55174. if (noiseTextureData && noiseTextureSize) {
  55175. var fetchedColorR = BABYLON.Tools.FetchR(particle.position.y, particle.position.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55176. var fetchedColorG = BABYLON.Tools.FetchR(particle.position.x + 0.33, particle.position.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55177. var fetchedColorB = BABYLON.Tools.FetchR(particle.position.x - 0.33, particle.position.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55178. var force = BABYLON.Tmp.Vector3[0];
  55179. var scaledForce = BABYLON.Tmp.Vector3[1];
  55180. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  55181. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  55182. particle.direction.addInPlace(scaledForce);
  55183. }
  55184. // Gravity
  55185. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55186. particle.direction.addInPlace(_this._scaledGravity);
  55187. // Size
  55188. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55189. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55190. if (currentGradient !== particle._currentSizeGradient) {
  55191. particle._currentSize1 = particle._currentSize2;
  55192. particle._currentSize2 = nextGradient.getFactor();
  55193. particle._currentSizeGradient = currentGradient;
  55194. }
  55195. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55196. });
  55197. }
  55198. if (_this._isAnimationSheetEnabled) {
  55199. particle.updateCellIndex();
  55200. }
  55201. }
  55202. };
  55203. var particle;
  55204. for (var index = 0; index < particles.length; index++) {
  55205. _loop_1();
  55206. }
  55207. };
  55208. }
  55209. /**
  55210. * Gets the current list of color gradients.
  55211. * You must use addColorGradient and removeColorGradient to udpate this list
  55212. * @returns the list of color gradients
  55213. */
  55214. ParticleSystem.prototype.getColorGradients = function () {
  55215. return this._colorGradients;
  55216. };
  55217. /**
  55218. * Gets the current list of size gradients.
  55219. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55220. * @returns the list of size gradients
  55221. */
  55222. ParticleSystem.prototype.getSizeGradients = function () {
  55223. return this._sizeGradients;
  55224. };
  55225. /**
  55226. * Gets the current list of life time gradients.
  55227. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55228. * @returns the list of life time gradients
  55229. */
  55230. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55231. return this._lifeTimeGradients;
  55232. };
  55233. /**
  55234. * Gets the current list of angular speed gradients.
  55235. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55236. * @returns the list of angular speed gradients
  55237. */
  55238. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  55239. return this._angularSpeedGradients;
  55240. };
  55241. /**
  55242. * Gets the current list of velocity gradients.
  55243. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55244. * @returns the list of velocity gradients
  55245. */
  55246. ParticleSystem.prototype.getVelocityGradients = function () {
  55247. return this._velocityGradients;
  55248. };
  55249. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55250. /**
  55251. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55252. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55253. */
  55254. get: function () {
  55255. if (this.particleEmitterType.direction1) {
  55256. return this.particleEmitterType.direction1;
  55257. }
  55258. return BABYLON.Vector3.Zero();
  55259. },
  55260. set: function (value) {
  55261. if (this.particleEmitterType.direction1) {
  55262. this.particleEmitterType.direction1 = value;
  55263. }
  55264. },
  55265. enumerable: true,
  55266. configurable: true
  55267. });
  55268. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55269. /**
  55270. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55271. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55272. */
  55273. get: function () {
  55274. if (this.particleEmitterType.direction2) {
  55275. return this.particleEmitterType.direction2;
  55276. }
  55277. return BABYLON.Vector3.Zero();
  55278. },
  55279. set: function (value) {
  55280. if (this.particleEmitterType.direction2) {
  55281. this.particleEmitterType.direction2 = value;
  55282. }
  55283. },
  55284. enumerable: true,
  55285. configurable: true
  55286. });
  55287. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55288. /**
  55289. * 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.
  55290. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55291. */
  55292. get: function () {
  55293. if (this.particleEmitterType.minEmitBox) {
  55294. return this.particleEmitterType.minEmitBox;
  55295. }
  55296. return BABYLON.Vector3.Zero();
  55297. },
  55298. set: function (value) {
  55299. if (this.particleEmitterType.minEmitBox) {
  55300. this.particleEmitterType.minEmitBox = value;
  55301. }
  55302. },
  55303. enumerable: true,
  55304. configurable: true
  55305. });
  55306. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55307. /**
  55308. * 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.
  55309. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55310. */
  55311. get: function () {
  55312. if (this.particleEmitterType.maxEmitBox) {
  55313. return this.particleEmitterType.maxEmitBox;
  55314. }
  55315. return BABYLON.Vector3.Zero();
  55316. },
  55317. set: function (value) {
  55318. if (this.particleEmitterType.maxEmitBox) {
  55319. this.particleEmitterType.maxEmitBox = value;
  55320. }
  55321. },
  55322. enumerable: true,
  55323. configurable: true
  55324. });
  55325. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55326. /**
  55327. * Sets a callback that will be triggered when the system is disposed
  55328. */
  55329. set: function (callback) {
  55330. if (this._onDisposeObserver) {
  55331. this.onDisposeObservable.remove(this._onDisposeObserver);
  55332. }
  55333. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55334. },
  55335. enumerable: true,
  55336. configurable: true
  55337. });
  55338. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55339. /**
  55340. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55341. */
  55342. get: function () {
  55343. return this._isAnimationSheetEnabled;
  55344. },
  55345. enumerable: true,
  55346. configurable: true
  55347. });
  55348. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55349. /**
  55350. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55351. */
  55352. get: function () {
  55353. return this._isBillboardBased;
  55354. },
  55355. set: function (value) {
  55356. if (this._isBillboardBased === value) {
  55357. return;
  55358. }
  55359. this._isBillboardBased = value;
  55360. this._resetEffect();
  55361. },
  55362. enumerable: true,
  55363. configurable: true
  55364. });
  55365. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55366. //end of Sub-emitter
  55367. /**
  55368. * Gets the current list of active particles
  55369. */
  55370. get: function () {
  55371. return this._particles;
  55372. },
  55373. enumerable: true,
  55374. configurable: true
  55375. });
  55376. /**
  55377. * Returns the string "ParticleSystem"
  55378. * @returns a string containing the class name
  55379. */
  55380. ParticleSystem.prototype.getClassName = function () {
  55381. return "ParticleSystem";
  55382. };
  55383. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55384. var newGradient = new BABYLON.FactorGradient();
  55385. newGradient.gradient = gradient;
  55386. newGradient.factor1 = factor;
  55387. newGradient.factor2 = factor2;
  55388. factorGradients.push(newGradient);
  55389. factorGradients.sort(function (a, b) {
  55390. if (a.gradient < b.gradient) {
  55391. return -1;
  55392. }
  55393. else if (a.gradient > b.gradient) {
  55394. return 1;
  55395. }
  55396. return 0;
  55397. });
  55398. };
  55399. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55400. if (!factorGradients) {
  55401. return;
  55402. }
  55403. var index = 0;
  55404. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55405. var factorGradient = factorGradients_1[_i];
  55406. if (factorGradient.gradient === gradient) {
  55407. factorGradients.splice(index, 1);
  55408. break;
  55409. }
  55410. index++;
  55411. }
  55412. };
  55413. /**
  55414. * Adds a new life time gradient
  55415. * @param gradient defines the gradient to use (between 0 and 1)
  55416. * @param factor defines the life time factor to affect to the specified gradient
  55417. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55418. * @returns the current particle system
  55419. */
  55420. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55421. if (!this._lifeTimeGradients) {
  55422. this._lifeTimeGradients = [];
  55423. }
  55424. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55425. return this;
  55426. };
  55427. /**
  55428. * Remove a specific life time gradient
  55429. * @param gradient defines the gradient to remove
  55430. * @returns the current particle system
  55431. */
  55432. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55433. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55434. return this;
  55435. };
  55436. /**
  55437. * Adds a new size gradient
  55438. * @param gradient defines the gradient to use (between 0 and 1)
  55439. * @param factor defines the size factor to affect to the specified gradient
  55440. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55441. * @returns the current particle system
  55442. */
  55443. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55444. if (!this._sizeGradients) {
  55445. this._sizeGradients = [];
  55446. }
  55447. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55448. return this;
  55449. };
  55450. /**
  55451. * Remove a specific size gradient
  55452. * @param gradient defines the gradient to remove
  55453. * @returns the current particle system
  55454. */
  55455. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55456. this._removeFactorGradient(this._sizeGradients, gradient);
  55457. return this;
  55458. };
  55459. /**
  55460. * Adds a new angular speed gradient
  55461. * @param gradient defines the gradient to use (between 0 and 1)
  55462. * @param factor defines the size factor to affect to the specified gradient
  55463. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55464. * @returns the current particle system
  55465. */
  55466. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55467. if (!this._angularSpeedGradients) {
  55468. this._angularSpeedGradients = [];
  55469. }
  55470. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55471. return this;
  55472. };
  55473. /**
  55474. * Remove a specific angular speed gradient
  55475. * @param gradient defines the gradient to remove
  55476. * @returns the current particle system
  55477. */
  55478. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55479. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55480. return this;
  55481. };
  55482. /**
  55483. * Adds a new velocity gradient
  55484. * @param gradient defines the gradient to use (between 0 and 1)
  55485. * @param factor defines the size factor to affect to the specified gradient
  55486. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55487. * @returns the current particle system
  55488. */
  55489. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55490. if (!this._velocityGradients) {
  55491. this._velocityGradients = [];
  55492. }
  55493. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55494. return this;
  55495. };
  55496. /**
  55497. * Remove a specific velocity gradient
  55498. * @param gradient defines the gradient to remove
  55499. * @returns the current particle system
  55500. */
  55501. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55502. this._removeFactorGradient(this._velocityGradients, gradient);
  55503. return this;
  55504. };
  55505. /**
  55506. * Adds a new color gradient
  55507. * @param gradient defines the gradient to use (between 0 and 1)
  55508. * @param color defines the color to affect to the specified gradient
  55509. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55510. */
  55511. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55512. if (!this._colorGradients) {
  55513. this._colorGradients = [];
  55514. }
  55515. var colorGradient = new BABYLON.ColorGradient();
  55516. colorGradient.gradient = gradient;
  55517. colorGradient.color1 = color;
  55518. colorGradient.color2 = color2;
  55519. this._colorGradients.push(colorGradient);
  55520. this._colorGradients.sort(function (a, b) {
  55521. if (a.gradient < b.gradient) {
  55522. return -1;
  55523. }
  55524. else if (a.gradient > b.gradient) {
  55525. return 1;
  55526. }
  55527. return 0;
  55528. });
  55529. return this;
  55530. };
  55531. /**
  55532. * Remove a specific color gradient
  55533. * @param gradient defines the gradient to remove
  55534. */
  55535. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55536. if (!this._colorGradients) {
  55537. return this;
  55538. }
  55539. var index = 0;
  55540. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55541. var colorGradient = _a[_i];
  55542. if (colorGradient.gradient === gradient) {
  55543. this._colorGradients.splice(index, 1);
  55544. break;
  55545. }
  55546. index++;
  55547. }
  55548. return this;
  55549. };
  55550. ParticleSystem.prototype._resetEffect = function () {
  55551. if (this._vertexBuffer) {
  55552. this._vertexBuffer.dispose();
  55553. this._vertexBuffer = null;
  55554. }
  55555. if (this._spriteBuffer) {
  55556. this._spriteBuffer.dispose();
  55557. this._spriteBuffer = null;
  55558. }
  55559. this._createVertexBuffers();
  55560. };
  55561. ParticleSystem.prototype._createVertexBuffers = function () {
  55562. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55563. if (this._isAnimationSheetEnabled) {
  55564. this._vertexBufferSize += 1;
  55565. }
  55566. if (!this._isBillboardBased) {
  55567. this._vertexBufferSize += 3;
  55568. }
  55569. var engine = this._scene.getEngine();
  55570. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55571. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55572. var dataOffset = 0;
  55573. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55574. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55575. dataOffset += 3;
  55576. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55577. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55578. dataOffset += 4;
  55579. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55580. this._vertexBuffers["angle"] = options;
  55581. dataOffset += 1;
  55582. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55583. this._vertexBuffers["size"] = size;
  55584. dataOffset += 2;
  55585. if (this._isAnimationSheetEnabled) {
  55586. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55587. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55588. dataOffset += 1;
  55589. }
  55590. if (!this._isBillboardBased) {
  55591. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55592. this._vertexBuffers["direction"] = directionBuffer;
  55593. dataOffset += 3;
  55594. }
  55595. var offsets;
  55596. if (this._useInstancing) {
  55597. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55598. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55599. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55600. }
  55601. else {
  55602. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55603. dataOffset += 2;
  55604. }
  55605. this._vertexBuffers["offset"] = offsets;
  55606. };
  55607. ParticleSystem.prototype._createIndexBuffer = function () {
  55608. if (this._useInstancing) {
  55609. return;
  55610. }
  55611. var indices = [];
  55612. var index = 0;
  55613. for (var count = 0; count < this._capacity; count++) {
  55614. indices.push(index);
  55615. indices.push(index + 1);
  55616. indices.push(index + 2);
  55617. indices.push(index);
  55618. indices.push(index + 2);
  55619. indices.push(index + 3);
  55620. index += 4;
  55621. }
  55622. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55623. };
  55624. /**
  55625. * Gets the maximum number of particles active at the same time.
  55626. * @returns The max number of active particles.
  55627. */
  55628. ParticleSystem.prototype.getCapacity = function () {
  55629. return this._capacity;
  55630. };
  55631. /**
  55632. * Gets Wether there are still active particles in the system.
  55633. * @returns True if it is alive, otherwise false.
  55634. */
  55635. ParticleSystem.prototype.isAlive = function () {
  55636. return this._alive;
  55637. };
  55638. /**
  55639. * Gets Wether the system has been started.
  55640. * @returns True if it has been started, otherwise false.
  55641. */
  55642. ParticleSystem.prototype.isStarted = function () {
  55643. return this._started;
  55644. };
  55645. /**
  55646. * Starts the particle system and begins to emit
  55647. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  55648. */
  55649. ParticleSystem.prototype.start = function (delay) {
  55650. var _this = this;
  55651. if (delay === void 0) { delay = 0; }
  55652. if (delay) {
  55653. setTimeout(function () {
  55654. _this.start(0);
  55655. }, delay);
  55656. return;
  55657. }
  55658. this._started = true;
  55659. this._stopped = false;
  55660. this._actualFrame = 0;
  55661. if (this.subEmitters && this.subEmitters.length != 0) {
  55662. this.activeSubSystems = new Array();
  55663. }
  55664. if (this.preWarmCycles) {
  55665. for (var index = 0; index < this.preWarmCycles; index++) {
  55666. this.animate(true);
  55667. }
  55668. }
  55669. };
  55670. /**
  55671. * Stops the particle system.
  55672. * @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.
  55673. */
  55674. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55675. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55676. this._stopped = true;
  55677. if (stopSubEmitters) {
  55678. this._stopSubEmitters();
  55679. }
  55680. };
  55681. // animation sheet
  55682. /**
  55683. * Remove all active particles
  55684. */
  55685. ParticleSystem.prototype.reset = function () {
  55686. this._stockParticles = [];
  55687. this._particles = [];
  55688. };
  55689. /**
  55690. * @hidden (for internal use only)
  55691. */
  55692. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55693. var offset = index * this._vertexBufferSize;
  55694. this._vertexData[offset++] = particle.position.x;
  55695. this._vertexData[offset++] = particle.position.y;
  55696. this._vertexData[offset++] = particle.position.z;
  55697. this._vertexData[offset++] = particle.color.r;
  55698. this._vertexData[offset++] = particle.color.g;
  55699. this._vertexData[offset++] = particle.color.b;
  55700. this._vertexData[offset++] = particle.color.a;
  55701. this._vertexData[offset++] = particle.angle;
  55702. this._vertexData[offset++] = particle.scale.x * particle.size;
  55703. this._vertexData[offset++] = particle.scale.y * particle.size;
  55704. if (this._isAnimationSheetEnabled) {
  55705. this._vertexData[offset++] = particle.cellIndex;
  55706. }
  55707. if (!this._isBillboardBased) {
  55708. if (particle._initialDirection) {
  55709. this._vertexData[offset++] = particle._initialDirection.x;
  55710. this._vertexData[offset++] = particle._initialDirection.y;
  55711. this._vertexData[offset++] = particle._initialDirection.z;
  55712. }
  55713. else {
  55714. this._vertexData[offset++] = particle.direction.x;
  55715. this._vertexData[offset++] = particle.direction.y;
  55716. this._vertexData[offset++] = particle.direction.z;
  55717. }
  55718. }
  55719. if (!this._useInstancing) {
  55720. if (this._isAnimationSheetEnabled) {
  55721. if (offsetX === 0)
  55722. offsetX = this._epsilon;
  55723. else if (offsetX === 1)
  55724. offsetX = 1 - this._epsilon;
  55725. if (offsetY === 0)
  55726. offsetY = this._epsilon;
  55727. else if (offsetY === 1)
  55728. offsetY = 1 - this._epsilon;
  55729. }
  55730. this._vertexData[offset++] = offsetX;
  55731. this._vertexData[offset++] = offsetY;
  55732. }
  55733. };
  55734. ParticleSystem.prototype._stopSubEmitters = function () {
  55735. if (!this.activeSubSystems) {
  55736. return;
  55737. }
  55738. this.activeSubSystems.forEach(function (subSystem) {
  55739. subSystem.stop(true);
  55740. });
  55741. this.activeSubSystems = new Array();
  55742. };
  55743. ParticleSystem.prototype._removeFromRoot = function () {
  55744. if (!this._rootParticleSystem) {
  55745. return;
  55746. }
  55747. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55748. if (index !== -1) {
  55749. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55750. }
  55751. };
  55752. // End of sub system methods
  55753. ParticleSystem.prototype._update = function (newParticles) {
  55754. // Update current
  55755. this._alive = this._particles.length > 0;
  55756. this.updateFunction(this._particles);
  55757. // Add new ones
  55758. var worldMatrix;
  55759. if (this.emitter.position) {
  55760. var emitterMesh = this.emitter;
  55761. worldMatrix = emitterMesh.getWorldMatrix();
  55762. }
  55763. else {
  55764. var emitterPosition = this.emitter;
  55765. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55766. }
  55767. var particle;
  55768. var _loop_2 = function () {
  55769. if (this_1._particles.length === this_1._capacity) {
  55770. return "break";
  55771. }
  55772. particle = this_1._createParticle();
  55773. this_1._particles.push(particle);
  55774. // Emitter
  55775. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55776. if (this_1.startPositionFunction) {
  55777. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55778. }
  55779. else {
  55780. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55781. }
  55782. if (this_1.startDirectionFunction) {
  55783. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55784. }
  55785. else {
  55786. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55787. }
  55788. if (emitPower === 0) {
  55789. if (!particle._initialDirection) {
  55790. particle._initialDirection = particle.direction.clone();
  55791. }
  55792. else {
  55793. particle._initialDirection.copyFrom(particle.direction);
  55794. }
  55795. }
  55796. else {
  55797. particle._initialDirection = null;
  55798. }
  55799. particle.direction.scaleInPlace(emitPower);
  55800. // Life time
  55801. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55802. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55803. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55804. var factorGradient1 = currentGradient;
  55805. var factorGradient2 = nextGradient;
  55806. var lifeTime1 = factorGradient1.getFactor();
  55807. var lifeTime2 = factorGradient2.getFactor();
  55808. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55809. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55810. });
  55811. }
  55812. else {
  55813. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55814. }
  55815. // Size
  55816. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55817. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55818. }
  55819. else {
  55820. particle._currentSizeGradient = this_1._sizeGradients[0];
  55821. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55822. particle.size = particle._currentSize1;
  55823. if (this_1._sizeGradients.length > 1) {
  55824. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55825. }
  55826. else {
  55827. particle._currentSize2 = particle._currentSize1;
  55828. }
  55829. }
  55830. // Size and scale
  55831. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55832. // Angle
  55833. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55834. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55835. }
  55836. else {
  55837. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55838. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55839. particle._currentAngularSpeed1 = particle.angularSpeed;
  55840. if (this_1._angularSpeedGradients.length > 1) {
  55841. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55842. }
  55843. else {
  55844. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55845. }
  55846. }
  55847. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55848. // Velocity
  55849. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55850. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55851. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55852. if (this_1._velocityGradients.length > 1) {
  55853. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55854. }
  55855. else {
  55856. particle._currentVelocity2 = particle._currentVelocity1;
  55857. }
  55858. }
  55859. // Color
  55860. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55861. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55862. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55863. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55864. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55865. }
  55866. else {
  55867. particle._currentColorGradient = this_1._colorGradients[0];
  55868. particle._currentColorGradient.getColorToRef(particle.color);
  55869. particle._currentColor1.copyFrom(particle.color);
  55870. if (this_1._colorGradients.length > 1) {
  55871. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55872. }
  55873. else {
  55874. particle._currentColor2.copyFrom(particle.color);
  55875. }
  55876. }
  55877. // Sheet
  55878. if (this_1._isAnimationSheetEnabled) {
  55879. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55880. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55881. }
  55882. };
  55883. var this_1 = this, step;
  55884. for (var index = 0; index < newParticles; index++) {
  55885. var state_1 = _loop_2();
  55886. if (state_1 === "break")
  55887. break;
  55888. }
  55889. };
  55890. /** @hidden */
  55891. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55892. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55893. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55894. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55895. if (isAnimationSheetEnabled) {
  55896. attributeNamesOrOptions.push("cellIndex");
  55897. }
  55898. if (!isBillboardBased) {
  55899. attributeNamesOrOptions.push("direction");
  55900. }
  55901. return attributeNamesOrOptions;
  55902. };
  55903. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55904. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55905. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55906. if (isAnimationSheetEnabled) {
  55907. effectCreationOption.push("particlesInfos");
  55908. }
  55909. return effectCreationOption;
  55910. };
  55911. ParticleSystem.prototype._getEffect = function () {
  55912. if (this._customEffect) {
  55913. return this._customEffect;
  55914. }
  55915. ;
  55916. var defines = [];
  55917. if (this._scene.clipPlane) {
  55918. defines.push("#define CLIPPLANE");
  55919. }
  55920. if (this._isAnimationSheetEnabled) {
  55921. defines.push("#define ANIMATESHEET");
  55922. }
  55923. if (this._isBillboardBased) {
  55924. defines.push("#define BILLBOARD");
  55925. switch (this.billboardMode) {
  55926. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  55927. defines.push("#define BILLBOARDY");
  55928. break;
  55929. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  55930. default:
  55931. break;
  55932. }
  55933. }
  55934. // Effect
  55935. var join = defines.join("\n");
  55936. if (this._cachedDefines !== join) {
  55937. this._cachedDefines = join;
  55938. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55939. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55940. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55941. }
  55942. return this._effect;
  55943. };
  55944. /**
  55945. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55946. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55947. */
  55948. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55949. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55950. if (!this._started)
  55951. return;
  55952. if (!preWarmOnly) {
  55953. var effect = this._getEffect();
  55954. // Check
  55955. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55956. return;
  55957. if (this._currentRenderId === this._scene.getRenderId()) {
  55958. return;
  55959. }
  55960. this._currentRenderId = this._scene.getRenderId();
  55961. }
  55962. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55963. // determine the number of particles we need to create
  55964. var newParticles;
  55965. if (this.manualEmitCount > -1) {
  55966. newParticles = this.manualEmitCount;
  55967. this._newPartsExcess = 0;
  55968. this.manualEmitCount = 0;
  55969. }
  55970. else {
  55971. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55972. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55973. }
  55974. if (this._newPartsExcess > 1.0) {
  55975. newParticles += this._newPartsExcess >> 0;
  55976. this._newPartsExcess -= this._newPartsExcess >> 0;
  55977. }
  55978. this._alive = false;
  55979. if (!this._stopped) {
  55980. this._actualFrame += this._scaledUpdateSpeed;
  55981. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55982. this.stop();
  55983. }
  55984. else {
  55985. newParticles = 0;
  55986. }
  55987. this._update(newParticles);
  55988. // Stopped?
  55989. if (this._stopped) {
  55990. if (!this._alive) {
  55991. this._started = false;
  55992. if (this.onAnimationEnd) {
  55993. this.onAnimationEnd();
  55994. }
  55995. if (this.disposeOnStop) {
  55996. this._scene._toBeDisposed.push(this);
  55997. }
  55998. }
  55999. }
  56000. if (!preWarmOnly) {
  56001. // Update VBO
  56002. var offset = 0;
  56003. for (var index = 0; index < this._particles.length; index++) {
  56004. var particle = this._particles[index];
  56005. this._appendParticleVertices(offset, particle);
  56006. offset += this._useInstancing ? 1 : 4;
  56007. }
  56008. if (this._vertexBuffer) {
  56009. this._vertexBuffer.update(this._vertexData);
  56010. }
  56011. }
  56012. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56013. this.stop();
  56014. }
  56015. };
  56016. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56017. this._appendParticleVertex(offset++, particle, 0, 0);
  56018. if (!this._useInstancing) {
  56019. this._appendParticleVertex(offset++, particle, 1, 0);
  56020. this._appendParticleVertex(offset++, particle, 1, 1);
  56021. this._appendParticleVertex(offset++, particle, 0, 1);
  56022. }
  56023. };
  56024. /**
  56025. * Rebuilds the particle system.
  56026. */
  56027. ParticleSystem.prototype.rebuild = function () {
  56028. this._createIndexBuffer();
  56029. if (this._vertexBuffer) {
  56030. this._vertexBuffer._rebuild();
  56031. }
  56032. };
  56033. /**
  56034. * Is this system ready to be used/rendered
  56035. * @return true if the system is ready
  56036. */
  56037. ParticleSystem.prototype.isReady = function () {
  56038. var effect = this._getEffect();
  56039. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56040. return false;
  56041. }
  56042. return true;
  56043. };
  56044. /**
  56045. * Renders the particle system in its current state.
  56046. * @returns the current number of particles
  56047. */
  56048. ParticleSystem.prototype.render = function () {
  56049. var effect = this._getEffect();
  56050. // Check
  56051. if (!this.isReady() || !this._particles.length) {
  56052. return 0;
  56053. }
  56054. var engine = this._scene.getEngine();
  56055. // Render
  56056. engine.enableEffect(effect);
  56057. engine.setState(false);
  56058. var viewMatrix = this._scene.getViewMatrix();
  56059. effect.setTexture("diffuseSampler", this.particleTexture);
  56060. effect.setMatrix("view", viewMatrix);
  56061. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56062. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56063. var baseSize = this.particleTexture.getBaseSize();
  56064. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56065. }
  56066. effect.setVector2("translationPivot", this.translationPivot);
  56067. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56068. if (this._isBillboardBased) {
  56069. var camera = this._scene.activeCamera;
  56070. effect.setVector3("eyePosition", camera.globalPosition);
  56071. }
  56072. if (this._scene.clipPlane) {
  56073. var clipPlane = this._scene.clipPlane;
  56074. var invView = viewMatrix.clone();
  56075. invView.invert();
  56076. effect.setMatrix("invView", invView);
  56077. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56078. }
  56079. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56080. // Draw order
  56081. switch (this.blendMode) {
  56082. case ParticleSystem.BLENDMODE_ADD:
  56083. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56084. break;
  56085. case ParticleSystem.BLENDMODE_ONEONE:
  56086. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56087. break;
  56088. case ParticleSystem.BLENDMODE_STANDARD:
  56089. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56090. break;
  56091. }
  56092. if (this.forceDepthWrite) {
  56093. engine.setDepthWrite(true);
  56094. }
  56095. if (this._useInstancing) {
  56096. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56097. engine.unbindInstanceAttributes();
  56098. }
  56099. else {
  56100. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56101. }
  56102. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56103. return this._particles.length;
  56104. };
  56105. /**
  56106. * Disposes the particle system and free the associated resources
  56107. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56108. */
  56109. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56110. if (disposeTexture === void 0) { disposeTexture = true; }
  56111. if (this._vertexBuffer) {
  56112. this._vertexBuffer.dispose();
  56113. this._vertexBuffer = null;
  56114. }
  56115. if (this._spriteBuffer) {
  56116. this._spriteBuffer.dispose();
  56117. this._spriteBuffer = null;
  56118. }
  56119. if (this._indexBuffer) {
  56120. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56121. this._indexBuffer = null;
  56122. }
  56123. if (disposeTexture && this.particleTexture) {
  56124. this.particleTexture.dispose();
  56125. this.particleTexture = null;
  56126. }
  56127. if (disposeTexture && this.noiseTexture) {
  56128. this.noiseTexture.dispose();
  56129. this.noiseTexture = null;
  56130. }
  56131. this._removeFromRoot();
  56132. // Remove from scene
  56133. var index = this._scene.particleSystems.indexOf(this);
  56134. if (index > -1) {
  56135. this._scene.particleSystems.splice(index, 1);
  56136. }
  56137. // Callback
  56138. this.onDisposeObservable.notifyObservers(this);
  56139. this.onDisposeObservable.clear();
  56140. };
  56141. /**
  56142. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56143. * @param radius The radius of the sphere to emit from
  56144. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56145. * @returns the emitter
  56146. */
  56147. ParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56148. if (radius === void 0) { radius = 1; }
  56149. if (radiusRange === void 0) { radiusRange = 1; }
  56150. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56151. this.particleEmitterType = particleEmitter;
  56152. return particleEmitter;
  56153. };
  56154. /**
  56155. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56156. * @param radius The radius of the sphere to emit from
  56157. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56158. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56159. * @returns the emitter
  56160. */
  56161. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56162. if (radius === void 0) { radius = 1; }
  56163. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56164. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56165. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56166. this.particleEmitterType = particleEmitter;
  56167. return particleEmitter;
  56168. };
  56169. /**
  56170. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56171. * @param radius The radius of the cone to emit from
  56172. * @param angle The base angle of the cone
  56173. * @returns the emitter
  56174. */
  56175. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56176. if (radius === void 0) { radius = 1; }
  56177. if (angle === void 0) { angle = Math.PI / 4; }
  56178. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56179. this.particleEmitterType = particleEmitter;
  56180. return particleEmitter;
  56181. };
  56182. // 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.
  56183. /**
  56184. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56185. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56186. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56187. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56188. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56189. * @returns the emitter
  56190. */
  56191. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56192. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56193. this.particleEmitterType = particleEmitter;
  56194. this.direction1 = direction1;
  56195. this.direction2 = direction2;
  56196. this.minEmitBox = minEmitBox;
  56197. this.maxEmitBox = maxEmitBox;
  56198. return particleEmitter;
  56199. };
  56200. // Clone
  56201. /**
  56202. * Clones the particle system.
  56203. * @param name The name of the cloned object
  56204. * @param newEmitter The new emitter to use
  56205. * @returns the cloned particle system
  56206. */
  56207. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56208. var custom = null;
  56209. var program = null;
  56210. if (this.customShader != null) {
  56211. program = this.customShader;
  56212. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56213. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56214. }
  56215. else if (this._customEffect) {
  56216. custom = this._customEffect;
  56217. }
  56218. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56219. result.customShader = program;
  56220. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56221. if (newEmitter === undefined) {
  56222. newEmitter = this.emitter;
  56223. }
  56224. result.emitter = newEmitter;
  56225. if (this.particleTexture) {
  56226. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56227. }
  56228. if (!this.preventAutoStart) {
  56229. result.start();
  56230. }
  56231. return result;
  56232. };
  56233. /**
  56234. * Serializes the particle system to a JSON object.
  56235. * @returns the JSON object
  56236. */
  56237. ParticleSystem.prototype.serialize = function () {
  56238. var serializationObject = {};
  56239. ParticleSystem._Serialize(serializationObject, this);
  56240. serializationObject.textureMask = this.textureMask.asArray();
  56241. serializationObject.customShader = this.customShader;
  56242. serializationObject.preventAutoStart = this.preventAutoStart;
  56243. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56244. return serializationObject;
  56245. };
  56246. /** @hidden */
  56247. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56248. serializationObject.name = particleSystem.name;
  56249. serializationObject.id = particleSystem.id;
  56250. serializationObject.capacity = particleSystem.getCapacity();
  56251. // Emitter
  56252. if (particleSystem.emitter.position) {
  56253. var emitterMesh = particleSystem.emitter;
  56254. serializationObject.emitterId = emitterMesh.id;
  56255. }
  56256. else {
  56257. var emitterPosition = particleSystem.emitter;
  56258. serializationObject.emitter = emitterPosition.asArray();
  56259. }
  56260. // Emitter
  56261. if (particleSystem.particleEmitterType) {
  56262. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56263. }
  56264. if (particleSystem.particleTexture) {
  56265. serializationObject.textureName = particleSystem.particleTexture.name;
  56266. }
  56267. // Animations
  56268. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56269. // Particle system
  56270. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56271. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56272. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56273. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56274. serializationObject.minSize = particleSystem.minSize;
  56275. serializationObject.maxSize = particleSystem.maxSize;
  56276. serializationObject.minScaleX = particleSystem.minScaleX;
  56277. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56278. serializationObject.minScaleY = particleSystem.minScaleY;
  56279. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56280. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56281. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56282. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56283. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56284. serializationObject.emitRate = particleSystem.emitRate;
  56285. serializationObject.gravity = particleSystem.gravity.asArray();
  56286. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  56287. serializationObject.color1 = particleSystem.color1.asArray();
  56288. serializationObject.color2 = particleSystem.color2.asArray();
  56289. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56290. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56291. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56292. serializationObject.blendMode = particleSystem.blendMode;
  56293. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56294. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56295. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56296. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56297. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56298. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56299. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56300. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56301. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56302. var colorGradients = particleSystem.getColorGradients();
  56303. if (colorGradients) {
  56304. serializationObject.colorGradients = [];
  56305. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56306. var colorGradient = colorGradients_1[_i];
  56307. var serializedGradient = {
  56308. gradient: colorGradient.gradient,
  56309. color1: colorGradient.color1.asArray()
  56310. };
  56311. if (colorGradient.color2) {
  56312. serializedGradient.color2 = colorGradient.color2.asArray();
  56313. }
  56314. serializationObject.colorGradients.push(serializedGradient);
  56315. }
  56316. }
  56317. var sizeGradients = particleSystem.getSizeGradients();
  56318. if (sizeGradients) {
  56319. serializationObject.sizeGradients = [];
  56320. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56321. var sizeGradient = sizeGradients_1[_a];
  56322. var serializedGradient = {
  56323. gradient: sizeGradient.gradient,
  56324. factor1: sizeGradient.factor1
  56325. };
  56326. if (sizeGradient.factor2 !== undefined) {
  56327. serializedGradient.factor2 = sizeGradient.factor2;
  56328. }
  56329. serializationObject.sizeGradients.push(serializedGradient);
  56330. }
  56331. }
  56332. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56333. if (angularSpeedGradients) {
  56334. serializationObject.angularSpeedGradients = [];
  56335. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56336. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56337. var serializedGradient = {
  56338. gradient: angularSpeedGradient.gradient,
  56339. factor1: angularSpeedGradient.factor1
  56340. };
  56341. if (angularSpeedGradient.factor2 !== undefined) {
  56342. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56343. }
  56344. serializationObject.angularSpeedGradients.push(serializedGradient);
  56345. }
  56346. }
  56347. var velocityGradients = particleSystem.getVelocityGradients();
  56348. if (velocityGradients) {
  56349. serializationObject.velocityGradients = [];
  56350. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56351. var velocityGradient = velocityGradients_1[_c];
  56352. var serializedGradient = {
  56353. gradient: velocityGradient.gradient,
  56354. factor1: velocityGradient.factor1
  56355. };
  56356. if (velocityGradient.factor2 !== undefined) {
  56357. serializedGradient.factor2 = velocityGradient.factor2;
  56358. }
  56359. serializationObject.velocityGradients.push(serializedGradient);
  56360. }
  56361. }
  56362. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  56363. var noiseTexture = particleSystem.noiseTexture;
  56364. serializationObject.noiseTexture = noiseTexture.serialize();
  56365. }
  56366. };
  56367. /** @hidden */
  56368. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56369. // Texture
  56370. if (parsedParticleSystem.textureName) {
  56371. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56372. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56373. }
  56374. // Emitter
  56375. if (parsedParticleSystem.emitterId === undefined) {
  56376. particleSystem.emitter = BABYLON.Vector3.Zero();
  56377. }
  56378. else if (parsedParticleSystem.emitterId) {
  56379. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56380. }
  56381. else {
  56382. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56383. }
  56384. // Misc.
  56385. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56386. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56387. }
  56388. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56389. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56390. }
  56391. // Animations
  56392. if (parsedParticleSystem.animations) {
  56393. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56394. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56395. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56396. }
  56397. }
  56398. if (parsedParticleSystem.autoAnimate) {
  56399. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56400. }
  56401. // Particle system
  56402. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56403. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56404. particleSystem.minSize = parsedParticleSystem.minSize;
  56405. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56406. if (parsedParticleSystem.minScaleX) {
  56407. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56408. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56409. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56410. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56411. }
  56412. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56413. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56414. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56415. }
  56416. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56417. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56418. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56419. }
  56420. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56421. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56422. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56423. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56424. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56425. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56426. if (parsedParticleSystem.noiseStrength) {
  56427. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  56428. }
  56429. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56430. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56431. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56432. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56433. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56434. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56435. if (parsedParticleSystem.colorGradients) {
  56436. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56437. var colorGradient = _a[_i];
  56438. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56439. }
  56440. }
  56441. if (parsedParticleSystem.sizeGradients) {
  56442. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56443. var sizeGradient = _c[_b];
  56444. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56445. }
  56446. }
  56447. if (parsedParticleSystem.angularSpeedGradients) {
  56448. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56449. var angularSpeedGradient = _e[_d];
  56450. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56451. }
  56452. }
  56453. if (parsedParticleSystem.velocityGradients) {
  56454. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56455. var velocityGradient = _g[_f];
  56456. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56457. }
  56458. }
  56459. if (parsedParticleSystem.noiseTexture) {
  56460. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  56461. }
  56462. // Emitter
  56463. var emitterType;
  56464. if (parsedParticleSystem.particleEmitterType) {
  56465. switch (parsedParticleSystem.particleEmitterType.type) {
  56466. case "SphereParticleEmitter":
  56467. emitterType = new BABYLON.SphereParticleEmitter();
  56468. break;
  56469. case "SphereDirectedParticleEmitter":
  56470. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56471. break;
  56472. case "ConeEmitter":
  56473. case "ConeParticleEmitter":
  56474. emitterType = new BABYLON.ConeParticleEmitter();
  56475. break;
  56476. case "BoxEmitter":
  56477. case "BoxParticleEmitter":
  56478. default:
  56479. emitterType = new BABYLON.BoxParticleEmitter();
  56480. break;
  56481. }
  56482. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56483. }
  56484. else {
  56485. emitterType = new BABYLON.BoxParticleEmitter();
  56486. emitterType.parse(parsedParticleSystem);
  56487. }
  56488. particleSystem.particleEmitterType = emitterType;
  56489. // Animation sheet
  56490. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56491. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56492. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56493. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56494. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56495. };
  56496. /**
  56497. * Parses a JSON object to create a particle system.
  56498. * @param parsedParticleSystem The JSON object to parse
  56499. * @param scene The scene to create the particle system in
  56500. * @param rootUrl The root url to use to load external dependencies like texture
  56501. * @returns the Parsed particle system
  56502. */
  56503. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56504. var name = parsedParticleSystem.name;
  56505. var custom = null;
  56506. var program = null;
  56507. if (parsedParticleSystem.customShader) {
  56508. program = parsedParticleSystem.customShader;
  56509. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56510. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56511. }
  56512. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56513. particleSystem.customShader = program;
  56514. if (parsedParticleSystem.id) {
  56515. particleSystem.id = parsedParticleSystem.id;
  56516. }
  56517. // Auto start
  56518. if (parsedParticleSystem.preventAutoStart) {
  56519. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56520. }
  56521. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56522. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56523. if (!particleSystem.preventAutoStart) {
  56524. particleSystem.start();
  56525. }
  56526. return particleSystem;
  56527. };
  56528. /**
  56529. * Source color is added to the destination color without alpha affecting the result.
  56530. */
  56531. ParticleSystem.BLENDMODE_ONEONE = 0;
  56532. /**
  56533. * Blend current color and particle color using particle’s alpha.
  56534. */
  56535. ParticleSystem.BLENDMODE_STANDARD = 1;
  56536. /**
  56537. * Add current color and particle color multiplied by particle’s alpha.
  56538. */
  56539. ParticleSystem.BLENDMODE_ADD = 2;
  56540. return ParticleSystem;
  56541. }());
  56542. BABYLON.ParticleSystem = ParticleSystem;
  56543. })(BABYLON || (BABYLON = {}));
  56544. //# sourceMappingURL=babylon.particleSystem.js.map
  56545. var BABYLON;
  56546. (function (BABYLON) {
  56547. /**
  56548. * Particle emitter emitting particles from the inside of a box.
  56549. * It emits the particles randomly between 2 given directions.
  56550. */
  56551. var BoxParticleEmitter = /** @class */ (function () {
  56552. /**
  56553. * Creates a new instance BoxParticleEmitter
  56554. */
  56555. function BoxParticleEmitter() {
  56556. /**
  56557. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56558. */
  56559. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56560. /**
  56561. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56562. */
  56563. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56564. /**
  56565. * 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.
  56566. */
  56567. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56568. /**
  56569. * 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.
  56570. */
  56571. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56572. }
  56573. /**
  56574. * Called by the particle System when the direction is computed for the created particle.
  56575. * @param worldMatrix is the world matrix of the particle system
  56576. * @param directionToUpdate is the direction vector to update with the result
  56577. * @param particle is the particle we are computed the direction for
  56578. */
  56579. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56580. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56581. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56582. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56583. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56584. };
  56585. /**
  56586. * Called by the particle System when the position is computed for the created particle.
  56587. * @param worldMatrix is the world matrix of the particle system
  56588. * @param positionToUpdate is the position vector to update with the result
  56589. * @param particle is the particle we are computed the position for
  56590. */
  56591. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56592. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56593. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56594. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56595. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56596. };
  56597. /**
  56598. * Clones the current emitter and returns a copy of it
  56599. * @returns the new emitter
  56600. */
  56601. BoxParticleEmitter.prototype.clone = function () {
  56602. var newOne = new BoxParticleEmitter();
  56603. BABYLON.Tools.DeepCopy(this, newOne);
  56604. return newOne;
  56605. };
  56606. /**
  56607. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56608. * @param effect defines the update shader
  56609. */
  56610. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56611. effect.setVector3("direction1", this.direction1);
  56612. effect.setVector3("direction2", this.direction2);
  56613. effect.setVector3("minEmitBox", this.minEmitBox);
  56614. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56615. };
  56616. /**
  56617. * Returns a string to use to update the GPU particles update shader
  56618. * @returns a string containng the defines string
  56619. */
  56620. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56621. return "#define BOXEMITTER";
  56622. };
  56623. /**
  56624. * Returns the string "BoxParticleEmitter"
  56625. * @returns a string containing the class name
  56626. */
  56627. BoxParticleEmitter.prototype.getClassName = function () {
  56628. return "BoxParticleEmitter";
  56629. };
  56630. /**
  56631. * Serializes the particle system to a JSON object.
  56632. * @returns the JSON object
  56633. */
  56634. BoxParticleEmitter.prototype.serialize = function () {
  56635. var serializationObject = {};
  56636. serializationObject.type = this.getClassName();
  56637. serializationObject.direction1 = this.direction1.asArray();
  56638. serializationObject.direction2 = this.direction2.asArray();
  56639. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56640. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56641. return serializationObject;
  56642. };
  56643. /**
  56644. * Parse properties from a JSON object
  56645. * @param serializationObject defines the JSON object
  56646. */
  56647. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56648. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56649. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56650. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56651. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56652. };
  56653. return BoxParticleEmitter;
  56654. }());
  56655. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56656. })(BABYLON || (BABYLON = {}));
  56657. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56658. var BABYLON;
  56659. (function (BABYLON) {
  56660. /**
  56661. * Particle emitter emitting particles from the inside of a cone.
  56662. * It emits the particles alongside the cone volume from the base to the particle.
  56663. * The emission direction might be randomized.
  56664. */
  56665. var ConeParticleEmitter = /** @class */ (function () {
  56666. /**
  56667. * Creates a new instance ConeParticleEmitter
  56668. * @param radius the radius of the emission cone (1 by default)
  56669. * @param angles the cone base angle (PI by default)
  56670. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56671. */
  56672. function ConeParticleEmitter(radius, angle,
  56673. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56674. directionRandomizer) {
  56675. if (radius === void 0) { radius = 1; }
  56676. if (angle === void 0) { angle = Math.PI; }
  56677. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56678. this.directionRandomizer = directionRandomizer;
  56679. /**
  56680. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56681. */
  56682. this.radiusRange = 1;
  56683. /**
  56684. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56685. */
  56686. this.heightRange = 1;
  56687. this.angle = angle;
  56688. this.radius = radius;
  56689. }
  56690. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56691. /**
  56692. * Gets or sets the radius of the emission cone
  56693. */
  56694. get: function () {
  56695. return this._radius;
  56696. },
  56697. set: function (value) {
  56698. this._radius = value;
  56699. this._buildHeight();
  56700. },
  56701. enumerable: true,
  56702. configurable: true
  56703. });
  56704. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56705. /**
  56706. * Gets or sets the angle of the emission cone
  56707. */
  56708. get: function () {
  56709. return this._angle;
  56710. },
  56711. set: function (value) {
  56712. this._angle = value;
  56713. this._buildHeight();
  56714. },
  56715. enumerable: true,
  56716. configurable: true
  56717. });
  56718. ConeParticleEmitter.prototype._buildHeight = function () {
  56719. if (this._angle !== 0) {
  56720. this._height = this._radius / Math.tan(this._angle / 2);
  56721. }
  56722. else {
  56723. this._height = 1;
  56724. }
  56725. };
  56726. /**
  56727. * Called by the particle System when the direction is computed for the created particle.
  56728. * @param worldMatrix is the world matrix of the particle system
  56729. * @param directionToUpdate is the direction vector to update with the result
  56730. * @param particle is the particle we are computed the direction for
  56731. */
  56732. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56733. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56734. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56735. }
  56736. else {
  56737. // measure the direction Vector from the emitter to the particle.
  56738. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56739. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56740. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56741. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56742. direction.x += randX;
  56743. direction.y += randY;
  56744. direction.z += randZ;
  56745. direction.normalize();
  56746. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56747. }
  56748. };
  56749. /**
  56750. * Called by the particle System when the position is computed for the created particle.
  56751. * @param worldMatrix is the world matrix of the particle system
  56752. * @param positionToUpdate is the position vector to update with the result
  56753. * @param particle is the particle we are computed the position for
  56754. */
  56755. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56756. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56757. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56758. // Better distribution in a cone at normal angles.
  56759. h = 1 - h * h;
  56760. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56761. radius = radius * h;
  56762. var randX = radius * Math.sin(s);
  56763. var randZ = radius * Math.cos(s);
  56764. var randY = h * this._height;
  56765. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56766. };
  56767. /**
  56768. * Clones the current emitter and returns a copy of it
  56769. * @returns the new emitter
  56770. */
  56771. ConeParticleEmitter.prototype.clone = function () {
  56772. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56773. BABYLON.Tools.DeepCopy(this, newOne);
  56774. return newOne;
  56775. };
  56776. /**
  56777. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56778. * @param effect defines the update shader
  56779. */
  56780. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56781. effect.setFloat2("radius", this._radius, this.radiusRange);
  56782. effect.setFloat("coneAngle", this._angle);
  56783. effect.setFloat2("height", this._height, this.heightRange);
  56784. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56785. };
  56786. /**
  56787. * Returns a string to use to update the GPU particles update shader
  56788. * @returns a string containng the defines string
  56789. */
  56790. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56791. return "#define CONEEMITTER";
  56792. };
  56793. /**
  56794. * Returns the string "ConeParticleEmitter"
  56795. * @returns a string containing the class name
  56796. */
  56797. ConeParticleEmitter.prototype.getClassName = function () {
  56798. return "ConeParticleEmitter";
  56799. };
  56800. /**
  56801. * Serializes the particle system to a JSON object.
  56802. * @returns the JSON object
  56803. */
  56804. ConeParticleEmitter.prototype.serialize = function () {
  56805. var serializationObject = {};
  56806. serializationObject.type = this.getClassName();
  56807. serializationObject.radius = this._radius;
  56808. serializationObject.angle = this._angle;
  56809. serializationObject.directionRandomizer = this.directionRandomizer;
  56810. return serializationObject;
  56811. };
  56812. /**
  56813. * Parse properties from a JSON object
  56814. * @param serializationObject defines the JSON object
  56815. */
  56816. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56817. this.radius = serializationObject.radius;
  56818. this.angle = serializationObject.angle;
  56819. this.directionRandomizer = serializationObject.directionRandomizer;
  56820. };
  56821. return ConeParticleEmitter;
  56822. }());
  56823. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56824. })(BABYLON || (BABYLON = {}));
  56825. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56826. var BABYLON;
  56827. (function (BABYLON) {
  56828. /**
  56829. * Particle emitter emitting particles from the inside of a sphere.
  56830. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56831. */
  56832. var SphereParticleEmitter = /** @class */ (function () {
  56833. /**
  56834. * Creates a new instance SphereParticleEmitter
  56835. * @param radius the radius of the emission sphere (1 by default)
  56836. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  56837. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56838. */
  56839. function SphereParticleEmitter(
  56840. /**
  56841. * The radius of the emission sphere.
  56842. */
  56843. radius,
  56844. /**
  56845. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  56846. */
  56847. radiusRange,
  56848. /**
  56849. * How much to randomize the particle direction [0-1].
  56850. */
  56851. directionRandomizer) {
  56852. if (radius === void 0) { radius = 1; }
  56853. if (radiusRange === void 0) { radiusRange = 1; }
  56854. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56855. this.radius = radius;
  56856. this.radiusRange = radiusRange;
  56857. this.directionRandomizer = directionRandomizer;
  56858. }
  56859. /**
  56860. * Called by the particle System when the direction is computed for the created particle.
  56861. * @param worldMatrix is the world matrix of the particle system
  56862. * @param directionToUpdate is the direction vector to update with the result
  56863. * @param particle is the particle we are computed the direction for
  56864. */
  56865. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56866. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56867. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56868. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56869. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56870. direction.x += randX;
  56871. direction.y += randY;
  56872. direction.z += randZ;
  56873. direction.normalize();
  56874. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56875. };
  56876. /**
  56877. * Called by the particle System when the position is computed for the created particle.
  56878. * @param worldMatrix is the world matrix of the particle system
  56879. * @param positionToUpdate is the position vector to update with the result
  56880. * @param particle is the particle we are computed the position for
  56881. */
  56882. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56883. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56884. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56885. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56886. var theta = Math.acos(2 * v - 1);
  56887. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56888. var randY = randRadius * Math.cos(theta);
  56889. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56890. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56891. };
  56892. /**
  56893. * Clones the current emitter and returns a copy of it
  56894. * @returns the new emitter
  56895. */
  56896. SphereParticleEmitter.prototype.clone = function () {
  56897. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56898. BABYLON.Tools.DeepCopy(this, newOne);
  56899. return newOne;
  56900. };
  56901. /**
  56902. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56903. * @param effect defines the update shader
  56904. */
  56905. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56906. effect.setFloat("radius", this.radius);
  56907. effect.setFloat("radiusRange", this.radiusRange);
  56908. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56909. };
  56910. /**
  56911. * Returns a string to use to update the GPU particles update shader
  56912. * @returns a string containng the defines string
  56913. */
  56914. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56915. return "#define SPHEREEMITTER";
  56916. };
  56917. /**
  56918. * Returns the string "SphereParticleEmitter"
  56919. * @returns a string containing the class name
  56920. */
  56921. SphereParticleEmitter.prototype.getClassName = function () {
  56922. return "SphereParticleEmitter";
  56923. };
  56924. /**
  56925. * Serializes the particle system to a JSON object.
  56926. * @returns the JSON object
  56927. */
  56928. SphereParticleEmitter.prototype.serialize = function () {
  56929. var serializationObject = {};
  56930. serializationObject.type = this.getClassName();
  56931. serializationObject.radius = this.radius;
  56932. serializationObject.radiusRange = this.radiusRange;
  56933. serializationObject.directionRandomizer = this.directionRandomizer;
  56934. return serializationObject;
  56935. };
  56936. /**
  56937. * Parse properties from a JSON object
  56938. * @param serializationObject defines the JSON object
  56939. */
  56940. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56941. this.radius = serializationObject.radius;
  56942. this.radiusRange = serializationObject.radiusRange;
  56943. this.directionRandomizer = serializationObject.directionRandomizer;
  56944. };
  56945. return SphereParticleEmitter;
  56946. }());
  56947. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56948. /**
  56949. * Particle emitter emitting particles from the inside of a sphere.
  56950. * It emits the particles randomly between two vectors.
  56951. */
  56952. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56953. __extends(SphereDirectedParticleEmitter, _super);
  56954. /**
  56955. * Creates a new instance SphereDirectedParticleEmitter
  56956. * @param radius the radius of the emission sphere (1 by default)
  56957. * @param direction1 the min limit of the emission direction (up vector by default)
  56958. * @param direction2 the max limit of the emission direction (up vector by default)
  56959. */
  56960. function SphereDirectedParticleEmitter(radius,
  56961. /**
  56962. * The min limit of the emission direction.
  56963. */
  56964. direction1,
  56965. /**
  56966. * The max limit of the emission direction.
  56967. */
  56968. direction2) {
  56969. if (radius === void 0) { radius = 1; }
  56970. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56971. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56972. var _this = _super.call(this, radius) || this;
  56973. _this.direction1 = direction1;
  56974. _this.direction2 = direction2;
  56975. return _this;
  56976. }
  56977. /**
  56978. * Called by the particle System when the direction is computed for the created particle.
  56979. * @param worldMatrix is the world matrix of the particle system
  56980. * @param directionToUpdate is the direction vector to update with the result
  56981. * @param particle is the particle we are computed the direction for
  56982. */
  56983. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56984. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56985. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56986. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56987. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56988. };
  56989. /**
  56990. * Clones the current emitter and returns a copy of it
  56991. * @returns the new emitter
  56992. */
  56993. SphereDirectedParticleEmitter.prototype.clone = function () {
  56994. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56995. BABYLON.Tools.DeepCopy(this, newOne);
  56996. return newOne;
  56997. };
  56998. /**
  56999. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57000. * @param effect defines the update shader
  57001. */
  57002. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57003. effect.setFloat("radius", this.radius);
  57004. effect.setFloat("radiusRange", this.radiusRange);
  57005. effect.setVector3("direction1", this.direction1);
  57006. effect.setVector3("direction2", this.direction2);
  57007. };
  57008. /**
  57009. * Returns a string to use to update the GPU particles update shader
  57010. * @returns a string containng the defines string
  57011. */
  57012. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57013. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57014. };
  57015. /**
  57016. * Returns the string "SphereDirectedParticleEmitter"
  57017. * @returns a string containing the class name
  57018. */
  57019. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57020. return "SphereDirectedParticleEmitter";
  57021. };
  57022. /**
  57023. * Serializes the particle system to a JSON object.
  57024. * @returns the JSON object
  57025. */
  57026. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57027. var serializationObject = _super.prototype.serialize.call(this);
  57028. serializationObject.direction1 = this.direction1.asArray();
  57029. serializationObject.direction2 = this.direction2.asArray();
  57030. return serializationObject;
  57031. };
  57032. /**
  57033. * Parse properties from a JSON object
  57034. * @param serializationObject defines the JSON object
  57035. */
  57036. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57037. _super.prototype.parse.call(this, serializationObject);
  57038. this.direction1.copyFrom(serializationObject.direction1);
  57039. this.direction2.copyFrom(serializationObject.direction2);
  57040. };
  57041. return SphereDirectedParticleEmitter;
  57042. }(SphereParticleEmitter));
  57043. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57044. })(BABYLON || (BABYLON = {}));
  57045. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57046. var BABYLON;
  57047. (function (BABYLON) {
  57048. // Adds the parsers to the scene parsers.
  57049. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  57050. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  57051. if (!individualParser) {
  57052. return;
  57053. }
  57054. // Particles Systems
  57055. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57056. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57057. var parsedParticleSystem = parsedData.particleSystems[index];
  57058. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  57059. }
  57060. }
  57061. });
  57062. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  57063. if (parsedParticleSystem.activeParticleCount) {
  57064. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57065. return ps;
  57066. }
  57067. else {
  57068. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57069. return ps;
  57070. }
  57071. });
  57072. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  57073. if (uniformsNames === void 0) { uniformsNames = []; }
  57074. if (samplers === void 0) { samplers = []; }
  57075. if (defines === void 0) { defines = ""; }
  57076. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  57077. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  57078. if (defines.indexOf(" BILLBOARD") === -1) {
  57079. defines += "\n#define BILLBOARD\n";
  57080. }
  57081. if (samplers.indexOf("diffuseSampler") === -1) {
  57082. samplers.push("diffuseSampler");
  57083. }
  57084. return this.createEffect({
  57085. vertex: "particles",
  57086. fragmentElement: fragmentName
  57087. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  57088. };
  57089. })(BABYLON || (BABYLON = {}));
  57090. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  57091. var BABYLON;
  57092. (function (BABYLON) {
  57093. var ShaderMaterial = /** @class */ (function (_super) {
  57094. __extends(ShaderMaterial, _super);
  57095. function ShaderMaterial(name, scene, shaderPath, options) {
  57096. var _this = _super.call(this, name, scene) || this;
  57097. _this._textures = {};
  57098. _this._textureArrays = {};
  57099. _this._floats = {};
  57100. _this._ints = {};
  57101. _this._floatsArrays = {};
  57102. _this._colors3 = {};
  57103. _this._colors3Arrays = {};
  57104. _this._colors4 = {};
  57105. _this._vectors2 = {};
  57106. _this._vectors3 = {};
  57107. _this._vectors4 = {};
  57108. _this._matrices = {};
  57109. _this._matrices3x3 = {};
  57110. _this._matrices2x2 = {};
  57111. _this._vectors2Arrays = {};
  57112. _this._vectors3Arrays = {};
  57113. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  57114. _this._shaderPath = shaderPath;
  57115. options.needAlphaBlending = options.needAlphaBlending || false;
  57116. options.needAlphaTesting = options.needAlphaTesting || false;
  57117. options.attributes = options.attributes || ["position", "normal", "uv"];
  57118. options.uniforms = options.uniforms || ["worldViewProjection"];
  57119. options.uniformBuffers = options.uniformBuffers || [];
  57120. options.samplers = options.samplers || [];
  57121. options.defines = options.defines || [];
  57122. _this._options = options;
  57123. return _this;
  57124. }
  57125. ShaderMaterial.prototype.getClassName = function () {
  57126. return "ShaderMaterial";
  57127. };
  57128. ShaderMaterial.prototype.needAlphaBlending = function () {
  57129. return this._options.needAlphaBlending;
  57130. };
  57131. ShaderMaterial.prototype.needAlphaTesting = function () {
  57132. return this._options.needAlphaTesting;
  57133. };
  57134. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  57135. if (this._options.uniforms.indexOf(uniformName) === -1) {
  57136. this._options.uniforms.push(uniformName);
  57137. }
  57138. };
  57139. ShaderMaterial.prototype.setTexture = function (name, texture) {
  57140. if (this._options.samplers.indexOf(name) === -1) {
  57141. this._options.samplers.push(name);
  57142. }
  57143. this._textures[name] = texture;
  57144. return this;
  57145. };
  57146. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  57147. if (this._options.samplers.indexOf(name) === -1) {
  57148. this._options.samplers.push(name);
  57149. }
  57150. this._checkUniform(name);
  57151. this._textureArrays[name] = textures;
  57152. return this;
  57153. };
  57154. ShaderMaterial.prototype.setFloat = function (name, value) {
  57155. this._checkUniform(name);
  57156. this._floats[name] = value;
  57157. return this;
  57158. };
  57159. ShaderMaterial.prototype.setInt = function (name, value) {
  57160. this._checkUniform(name);
  57161. this._ints[name] = value;
  57162. return this;
  57163. };
  57164. ShaderMaterial.prototype.setFloats = function (name, value) {
  57165. this._checkUniform(name);
  57166. this._floatsArrays[name] = value;
  57167. return this;
  57168. };
  57169. ShaderMaterial.prototype.setColor3 = function (name, value) {
  57170. this._checkUniform(name);
  57171. this._colors3[name] = value;
  57172. return this;
  57173. };
  57174. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  57175. this._checkUniform(name);
  57176. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  57177. color.toArray(arr, arr.length);
  57178. return arr;
  57179. }, []);
  57180. return this;
  57181. };
  57182. ShaderMaterial.prototype.setColor4 = function (name, value) {
  57183. this._checkUniform(name);
  57184. this._colors4[name] = value;
  57185. return this;
  57186. };
  57187. ShaderMaterial.prototype.setVector2 = function (name, value) {
  57188. this._checkUniform(name);
  57189. this._vectors2[name] = value;
  57190. return this;
  57191. };
  57192. ShaderMaterial.prototype.setVector3 = function (name, value) {
  57193. this._checkUniform(name);
  57194. this._vectors3[name] = value;
  57195. return this;
  57196. };
  57197. ShaderMaterial.prototype.setVector4 = function (name, value) {
  57198. this._checkUniform(name);
  57199. this._vectors4[name] = value;
  57200. return this;
  57201. };
  57202. ShaderMaterial.prototype.setMatrix = function (name, value) {
  57203. this._checkUniform(name);
  57204. this._matrices[name] = value;
  57205. return this;
  57206. };
  57207. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  57208. this._checkUniform(name);
  57209. this._matrices3x3[name] = value;
  57210. return this;
  57211. };
  57212. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  57213. this._checkUniform(name);
  57214. this._matrices2x2[name] = value;
  57215. return this;
  57216. };
  57217. ShaderMaterial.prototype.setArray2 = function (name, value) {
  57218. this._checkUniform(name);
  57219. this._vectors2Arrays[name] = value;
  57220. return this;
  57221. };
  57222. ShaderMaterial.prototype.setArray3 = function (name, value) {
  57223. this._checkUniform(name);
  57224. this._vectors3Arrays[name] = value;
  57225. return this;
  57226. };
  57227. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57228. if (!mesh) {
  57229. return true;
  57230. }
  57231. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  57232. return false;
  57233. }
  57234. return false;
  57235. };
  57236. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  57237. var scene = this.getScene();
  57238. var engine = scene.getEngine();
  57239. if (!this.checkReadyOnEveryCall) {
  57240. if (this._renderId === scene.getRenderId()) {
  57241. if (this._checkCache(scene, mesh, useInstances)) {
  57242. return true;
  57243. }
  57244. }
  57245. }
  57246. // Instances
  57247. var defines = [];
  57248. var attribs = [];
  57249. var fallbacks = new BABYLON.EffectFallbacks();
  57250. if (useInstances) {
  57251. defines.push("#define INSTANCES");
  57252. }
  57253. for (var index = 0; index < this._options.defines.length; index++) {
  57254. defines.push(this._options.defines[index]);
  57255. }
  57256. for (var index = 0; index < this._options.attributes.length; index++) {
  57257. attribs.push(this._options.attributes[index]);
  57258. }
  57259. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57260. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57261. defines.push("#define VERTEXCOLOR");
  57262. }
  57263. // Bones
  57264. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57265. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57266. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57267. if (mesh.numBoneInfluencers > 4) {
  57268. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57269. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57270. }
  57271. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57272. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57273. fallbacks.addCPUSkinningFallback(0, mesh);
  57274. if (this._options.uniforms.indexOf("mBones") === -1) {
  57275. this._options.uniforms.push("mBones");
  57276. }
  57277. }
  57278. else {
  57279. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57280. }
  57281. // Textures
  57282. for (var name in this._textures) {
  57283. if (!this._textures[name].isReady()) {
  57284. return false;
  57285. }
  57286. }
  57287. // Alpha test
  57288. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  57289. defines.push("#define ALPHATEST");
  57290. }
  57291. var previousEffect = this._effect;
  57292. var join = defines.join("\n");
  57293. this._effect = engine.createEffect(this._shaderPath, {
  57294. attributes: attribs,
  57295. uniformsNames: this._options.uniforms,
  57296. uniformBuffersNames: this._options.uniformBuffers,
  57297. samplers: this._options.samplers,
  57298. defines: join,
  57299. fallbacks: fallbacks,
  57300. onCompiled: this.onCompiled,
  57301. onError: this.onError
  57302. }, engine);
  57303. if (!this._effect.isReady()) {
  57304. return false;
  57305. }
  57306. if (previousEffect !== this._effect) {
  57307. scene.resetCachedMaterial();
  57308. }
  57309. this._renderId = scene.getRenderId();
  57310. return true;
  57311. };
  57312. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  57313. var scene = this.getScene();
  57314. if (!this._effect) {
  57315. return;
  57316. }
  57317. if (this._options.uniforms.indexOf("world") !== -1) {
  57318. this._effect.setMatrix("world", world);
  57319. }
  57320. if (this._options.uniforms.indexOf("worldView") !== -1) {
  57321. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  57322. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  57323. }
  57324. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  57325. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  57326. }
  57327. };
  57328. ShaderMaterial.prototype.bind = function (world, mesh) {
  57329. // Std values
  57330. this.bindOnlyWorldMatrix(world);
  57331. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  57332. if (this._options.uniforms.indexOf("view") !== -1) {
  57333. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  57334. }
  57335. if (this._options.uniforms.indexOf("projection") !== -1) {
  57336. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  57337. }
  57338. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  57339. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  57340. }
  57341. // Bones
  57342. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57343. var name;
  57344. // Texture
  57345. for (name in this._textures) {
  57346. this._effect.setTexture(name, this._textures[name]);
  57347. }
  57348. // Texture arrays
  57349. for (name in this._textureArrays) {
  57350. this._effect.setTextureArray(name, this._textureArrays[name]);
  57351. }
  57352. // Int
  57353. for (name in this._ints) {
  57354. this._effect.setInt(name, this._ints[name]);
  57355. }
  57356. // Float
  57357. for (name in this._floats) {
  57358. this._effect.setFloat(name, this._floats[name]);
  57359. }
  57360. // Floats
  57361. for (name in this._floatsArrays) {
  57362. this._effect.setArray(name, this._floatsArrays[name]);
  57363. }
  57364. // Color3
  57365. for (name in this._colors3) {
  57366. this._effect.setColor3(name, this._colors3[name]);
  57367. }
  57368. for (name in this._colors3Arrays) {
  57369. this._effect.setArray3(name, this._colors3Arrays[name]);
  57370. }
  57371. // Color4
  57372. for (name in this._colors4) {
  57373. var color = this._colors4[name];
  57374. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57375. }
  57376. // Vector2
  57377. for (name in this._vectors2) {
  57378. this._effect.setVector2(name, this._vectors2[name]);
  57379. }
  57380. // Vector3
  57381. for (name in this._vectors3) {
  57382. this._effect.setVector3(name, this._vectors3[name]);
  57383. }
  57384. // Vector4
  57385. for (name in this._vectors4) {
  57386. this._effect.setVector4(name, this._vectors4[name]);
  57387. }
  57388. // Matrix
  57389. for (name in this._matrices) {
  57390. this._effect.setMatrix(name, this._matrices[name]);
  57391. }
  57392. // Matrix 3x3
  57393. for (name in this._matrices3x3) {
  57394. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  57395. }
  57396. // Matrix 2x2
  57397. for (name in this._matrices2x2) {
  57398. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  57399. }
  57400. // Vector2Array
  57401. for (name in this._vectors2Arrays) {
  57402. this._effect.setArray2(name, this._vectors2Arrays[name]);
  57403. }
  57404. // Vector3Array
  57405. for (name in this._vectors3Arrays) {
  57406. this._effect.setArray3(name, this._vectors3Arrays[name]);
  57407. }
  57408. }
  57409. this._afterBind(mesh);
  57410. };
  57411. ShaderMaterial.prototype.getActiveTextures = function () {
  57412. var activeTextures = _super.prototype.getActiveTextures.call(this);
  57413. for (var name in this._textures) {
  57414. activeTextures.push(this._textures[name]);
  57415. }
  57416. for (var name in this._textureArrays) {
  57417. var array = this._textureArrays[name];
  57418. for (var index = 0; index < array.length; index++) {
  57419. activeTextures.push(array[index]);
  57420. }
  57421. }
  57422. return activeTextures;
  57423. };
  57424. ShaderMaterial.prototype.hasTexture = function (texture) {
  57425. if (_super.prototype.hasTexture.call(this, texture)) {
  57426. return true;
  57427. }
  57428. for (var name in this._textures) {
  57429. if (this._textures[name] === texture) {
  57430. return true;
  57431. }
  57432. }
  57433. for (var name in this._textureArrays) {
  57434. var array = this._textureArrays[name];
  57435. for (var index = 0; index < array.length; index++) {
  57436. if (array[index] === texture) {
  57437. return true;
  57438. }
  57439. }
  57440. }
  57441. return false;
  57442. };
  57443. ShaderMaterial.prototype.clone = function (name) {
  57444. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  57445. return newShaderMaterial;
  57446. };
  57447. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57448. if (forceDisposeTextures) {
  57449. var name;
  57450. for (name in this._textures) {
  57451. this._textures[name].dispose();
  57452. }
  57453. for (name in this._textureArrays) {
  57454. var array = this._textureArrays[name];
  57455. for (var index = 0; index < array.length; index++) {
  57456. array[index].dispose();
  57457. }
  57458. }
  57459. }
  57460. this._textures = {};
  57461. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57462. };
  57463. ShaderMaterial.prototype.serialize = function () {
  57464. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57465. serializationObject.customType = "BABYLON.ShaderMaterial";
  57466. serializationObject.options = this._options;
  57467. serializationObject.shaderPath = this._shaderPath;
  57468. var name;
  57469. // Texture
  57470. serializationObject.textures = {};
  57471. for (name in this._textures) {
  57472. serializationObject.textures[name] = this._textures[name].serialize();
  57473. }
  57474. // Texture arrays
  57475. serializationObject.textureArrays = {};
  57476. for (name in this._textureArrays) {
  57477. serializationObject.textureArrays[name] = [];
  57478. var array = this._textureArrays[name];
  57479. for (var index = 0; index < array.length; index++) {
  57480. serializationObject.textureArrays[name].push(array[index].serialize());
  57481. }
  57482. }
  57483. // Float
  57484. serializationObject.floats = {};
  57485. for (name in this._floats) {
  57486. serializationObject.floats[name] = this._floats[name];
  57487. }
  57488. // Float s
  57489. serializationObject.FloatArrays = {};
  57490. for (name in this._floatsArrays) {
  57491. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  57492. }
  57493. // Color3
  57494. serializationObject.colors3 = {};
  57495. for (name in this._colors3) {
  57496. serializationObject.colors3[name] = this._colors3[name].asArray();
  57497. }
  57498. // Color3 array
  57499. serializationObject.colors3Arrays = {};
  57500. for (name in this._colors3Arrays) {
  57501. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  57502. }
  57503. // Color4
  57504. serializationObject.colors4 = {};
  57505. for (name in this._colors4) {
  57506. serializationObject.colors4[name] = this._colors4[name].asArray();
  57507. }
  57508. // Vector2
  57509. serializationObject.vectors2 = {};
  57510. for (name in this._vectors2) {
  57511. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  57512. }
  57513. // Vector3
  57514. serializationObject.vectors3 = {};
  57515. for (name in this._vectors3) {
  57516. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  57517. }
  57518. // Vector4
  57519. serializationObject.vectors4 = {};
  57520. for (name in this._vectors4) {
  57521. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  57522. }
  57523. // Matrix
  57524. serializationObject.matrices = {};
  57525. for (name in this._matrices) {
  57526. serializationObject.matrices[name] = this._matrices[name].asArray();
  57527. }
  57528. // Matrix 3x3
  57529. serializationObject.matrices3x3 = {};
  57530. for (name in this._matrices3x3) {
  57531. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  57532. }
  57533. // Matrix 2x2
  57534. serializationObject.matrices2x2 = {};
  57535. for (name in this._matrices2x2) {
  57536. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  57537. }
  57538. // Vector2Array
  57539. serializationObject.vectors2Arrays = {};
  57540. for (name in this._vectors2Arrays) {
  57541. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  57542. }
  57543. // Vector3Array
  57544. serializationObject.vectors3Arrays = {};
  57545. for (name in this._vectors3Arrays) {
  57546. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  57547. }
  57548. return serializationObject;
  57549. };
  57550. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  57551. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  57552. var name;
  57553. // Texture
  57554. for (name in source.textures) {
  57555. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  57556. }
  57557. // Texture arrays
  57558. for (name in source.textureArrays) {
  57559. var array = source.textureArrays[name];
  57560. var textureArray = new Array();
  57561. for (var index = 0; index < array.length; index++) {
  57562. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  57563. }
  57564. material.setTextureArray(name, textureArray);
  57565. }
  57566. // Float
  57567. for (name in source.floats) {
  57568. material.setFloat(name, source.floats[name]);
  57569. }
  57570. // Float s
  57571. for (name in source.floatsArrays) {
  57572. material.setFloats(name, source.floatsArrays[name]);
  57573. }
  57574. // Color3
  57575. for (name in source.colors3) {
  57576. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  57577. }
  57578. // Color3 arrays
  57579. for (name in source.colors3Arrays) {
  57580. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  57581. if (i % 3 === 0) {
  57582. arr.push([num]);
  57583. }
  57584. else {
  57585. arr[arr.length - 1].push(num);
  57586. }
  57587. return arr;
  57588. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  57589. material.setColor3Array(name, colors);
  57590. }
  57591. // Color4
  57592. for (name in source.colors4) {
  57593. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  57594. }
  57595. // Vector2
  57596. for (name in source.vectors2) {
  57597. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  57598. }
  57599. // Vector3
  57600. for (name in source.vectors3) {
  57601. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  57602. }
  57603. // Vector4
  57604. for (name in source.vectors4) {
  57605. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  57606. }
  57607. // Matrix
  57608. for (name in source.matrices) {
  57609. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  57610. }
  57611. // Matrix 3x3
  57612. for (name in source.matrices3x3) {
  57613. material.setMatrix3x3(name, source.matrices3x3[name]);
  57614. }
  57615. // Matrix 2x2
  57616. for (name in source.matrices2x2) {
  57617. material.setMatrix2x2(name, source.matrices2x2[name]);
  57618. }
  57619. // Vector2Array
  57620. for (name in source.vectors2Arrays) {
  57621. material.setArray2(name, source.vectors2Arrays[name]);
  57622. }
  57623. // Vector3Array
  57624. for (name in source.vectors3Arrays) {
  57625. material.setArray3(name, source.vectors3Arrays[name]);
  57626. }
  57627. return material;
  57628. };
  57629. return ShaderMaterial;
  57630. }(BABYLON.Material));
  57631. BABYLON.ShaderMaterial = ShaderMaterial;
  57632. })(BABYLON || (BABYLON = {}));
  57633. //# sourceMappingURL=babylon.shaderMaterial.js.map
  57634. var BABYLON;
  57635. (function (BABYLON) {
  57636. var GroundMesh = /** @class */ (function (_super) {
  57637. __extends(GroundMesh, _super);
  57638. function GroundMesh(name, scene) {
  57639. var _this = _super.call(this, name, scene) || this;
  57640. _this.generateOctree = false;
  57641. return _this;
  57642. }
  57643. GroundMesh.prototype.getClassName = function () {
  57644. return "GroundMesh";
  57645. };
  57646. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  57647. get: function () {
  57648. return Math.min(this._subdivisionsX, this._subdivisionsY);
  57649. },
  57650. enumerable: true,
  57651. configurable: true
  57652. });
  57653. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  57654. get: function () {
  57655. return this._subdivisionsX;
  57656. },
  57657. enumerable: true,
  57658. configurable: true
  57659. });
  57660. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  57661. get: function () {
  57662. return this._subdivisionsY;
  57663. },
  57664. enumerable: true,
  57665. configurable: true
  57666. });
  57667. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  57668. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  57669. this._subdivisionsX = chunksCount;
  57670. this._subdivisionsY = chunksCount;
  57671. this.subdivide(chunksCount);
  57672. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  57673. };
  57674. /**
  57675. * Returns a height (y) value in the Worl system :
  57676. * the ground altitude at the coordinates (x, z) expressed in the World system.
  57677. * Returns the ground y position if (x, z) are outside the ground surface.
  57678. */
  57679. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  57680. var world = this.getWorldMatrix();
  57681. var invMat = BABYLON.Tmp.Matrix[5];
  57682. world.invertToRef(invMat);
  57683. var tmpVect = BABYLON.Tmp.Vector3[8];
  57684. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  57685. x = tmpVect.x;
  57686. z = tmpVect.z;
  57687. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57688. return this.position.y;
  57689. }
  57690. if (!this._heightQuads || this._heightQuads.length == 0) {
  57691. this._initHeightQuads();
  57692. this._computeHeightQuads();
  57693. }
  57694. var facet = this._getFacetAt(x, z);
  57695. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  57696. // return y in the World system
  57697. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  57698. return tmpVect.y;
  57699. };
  57700. /**
  57701. * Returns a normalized vector (Vector3) orthogonal to the ground
  57702. * at the ground coordinates (x, z) expressed in the World system.
  57703. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  57704. */
  57705. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  57706. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  57707. this.getNormalAtCoordinatesToRef(x, z, normal);
  57708. return normal;
  57709. };
  57710. /**
  57711. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  57712. * at the ground coordinates (x, z) expressed in the World system.
  57713. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  57714. * Returns the GroundMesh.
  57715. */
  57716. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  57717. var world = this.getWorldMatrix();
  57718. var tmpMat = BABYLON.Tmp.Matrix[5];
  57719. world.invertToRef(tmpMat);
  57720. var tmpVect = BABYLON.Tmp.Vector3[8];
  57721. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  57722. x = tmpVect.x;
  57723. z = tmpVect.z;
  57724. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57725. return this;
  57726. }
  57727. if (!this._heightQuads || this._heightQuads.length == 0) {
  57728. this._initHeightQuads();
  57729. this._computeHeightQuads();
  57730. }
  57731. var facet = this._getFacetAt(x, z);
  57732. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  57733. return this;
  57734. };
  57735. /**
  57736. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  57737. * if the ground has been updated.
  57738. * This can be used in the render loop.
  57739. * Returns the GroundMesh.
  57740. */
  57741. GroundMesh.prototype.updateCoordinateHeights = function () {
  57742. if (!this._heightQuads || this._heightQuads.length == 0) {
  57743. this._initHeightQuads();
  57744. }
  57745. this._computeHeightQuads();
  57746. return this;
  57747. };
  57748. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  57749. GroundMesh.prototype._getFacetAt = function (x, z) {
  57750. // retrieve col and row from x, z coordinates in the ground local system
  57751. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  57752. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  57753. var quad = this._heightQuads[row * this._subdivisionsX + col];
  57754. var facet;
  57755. if (z < quad.slope.x * x + quad.slope.y) {
  57756. facet = quad.facet1;
  57757. }
  57758. else {
  57759. facet = quad.facet2;
  57760. }
  57761. return facet;
  57762. };
  57763. // Creates and populates the heightMap array with "facet" elements :
  57764. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  57765. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57766. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57767. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57768. // Returns the GroundMesh.
  57769. GroundMesh.prototype._initHeightQuads = function () {
  57770. var subdivisionsX = this._subdivisionsX;
  57771. var subdivisionsY = this._subdivisionsY;
  57772. this._heightQuads = new Array();
  57773. for (var row = 0; row < subdivisionsY; row++) {
  57774. for (var col = 0; col < subdivisionsX; col++) {
  57775. 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) };
  57776. this._heightQuads[row * subdivisionsX + col] = quad;
  57777. }
  57778. }
  57779. return this;
  57780. };
  57781. // Compute each quad element values and update the the heightMap array :
  57782. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57783. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57784. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57785. // Returns the GroundMesh.
  57786. GroundMesh.prototype._computeHeightQuads = function () {
  57787. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57788. if (!positions) {
  57789. return this;
  57790. }
  57791. var v1 = BABYLON.Tmp.Vector3[3];
  57792. var v2 = BABYLON.Tmp.Vector3[2];
  57793. var v3 = BABYLON.Tmp.Vector3[1];
  57794. var v4 = BABYLON.Tmp.Vector3[0];
  57795. var v1v2 = BABYLON.Tmp.Vector3[4];
  57796. var v1v3 = BABYLON.Tmp.Vector3[5];
  57797. var v1v4 = BABYLON.Tmp.Vector3[6];
  57798. var norm1 = BABYLON.Tmp.Vector3[7];
  57799. var norm2 = BABYLON.Tmp.Vector3[8];
  57800. var i = 0;
  57801. var j = 0;
  57802. var k = 0;
  57803. var cd = 0; // 2D slope coefficient : z = cd * x + h
  57804. var h = 0;
  57805. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  57806. var d2 = 0;
  57807. var subdivisionsX = this._subdivisionsX;
  57808. var subdivisionsY = this._subdivisionsY;
  57809. for (var row = 0; row < subdivisionsY; row++) {
  57810. for (var col = 0; col < subdivisionsX; col++) {
  57811. i = col * 3;
  57812. j = row * (subdivisionsX + 1) * 3;
  57813. k = (row + 1) * (subdivisionsX + 1) * 3;
  57814. v1.x = positions[j + i];
  57815. v1.y = positions[j + i + 1];
  57816. v1.z = positions[j + i + 2];
  57817. v2.x = positions[j + i + 3];
  57818. v2.y = positions[j + i + 4];
  57819. v2.z = positions[j + i + 5];
  57820. v3.x = positions[k + i];
  57821. v3.y = positions[k + i + 1];
  57822. v3.z = positions[k + i + 2];
  57823. v4.x = positions[k + i + 3];
  57824. v4.y = positions[k + i + 4];
  57825. v4.z = positions[k + i + 5];
  57826. // 2D slope V1V4
  57827. cd = (v4.z - v1.z) / (v4.x - v1.x);
  57828. h = v1.z - cd * v1.x; // v1 belongs to the slope
  57829. // facet equations :
  57830. // we compute each facet normal vector
  57831. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  57832. // we compute the value d by applying the equation to v1 which belongs to the plane
  57833. // then we store the facet equation in a Vector4
  57834. v2.subtractToRef(v1, v1v2);
  57835. v3.subtractToRef(v1, v1v3);
  57836. v4.subtractToRef(v1, v1v4);
  57837. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  57838. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  57839. norm1.normalize();
  57840. norm2.normalize();
  57841. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  57842. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  57843. var quad = this._heightQuads[row * subdivisionsX + col];
  57844. quad.slope.copyFromFloats(cd, h);
  57845. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  57846. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  57847. }
  57848. }
  57849. return this;
  57850. };
  57851. GroundMesh.prototype.serialize = function (serializationObject) {
  57852. _super.prototype.serialize.call(this, serializationObject);
  57853. serializationObject.subdivisionsX = this._subdivisionsX;
  57854. serializationObject.subdivisionsY = this._subdivisionsY;
  57855. serializationObject.minX = this._minX;
  57856. serializationObject.maxX = this._maxX;
  57857. serializationObject.minZ = this._minZ;
  57858. serializationObject.maxZ = this._maxZ;
  57859. serializationObject.width = this._width;
  57860. serializationObject.height = this._height;
  57861. };
  57862. GroundMesh.Parse = function (parsedMesh, scene) {
  57863. var result = new GroundMesh(parsedMesh.name, scene);
  57864. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  57865. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  57866. result._minX = parsedMesh.minX;
  57867. result._maxX = parsedMesh.maxX;
  57868. result._minZ = parsedMesh.minZ;
  57869. result._maxZ = parsedMesh.maxZ;
  57870. result._width = parsedMesh.width;
  57871. result._height = parsedMesh.height;
  57872. return result;
  57873. };
  57874. return GroundMesh;
  57875. }(BABYLON.Mesh));
  57876. BABYLON.GroundMesh = GroundMesh;
  57877. })(BABYLON || (BABYLON = {}));
  57878. //# sourceMappingURL=babylon.groundMesh.js.map
  57879. var BABYLON;
  57880. (function (BABYLON) {
  57881. /**
  57882. * Creates an instance based on a source mesh.
  57883. */
  57884. var InstancedMesh = /** @class */ (function (_super) {
  57885. __extends(InstancedMesh, _super);
  57886. function InstancedMesh(name, source) {
  57887. var _this = _super.call(this, name, source.getScene()) || this;
  57888. source.instances.push(_this);
  57889. _this._sourceMesh = source;
  57890. _this.position.copyFrom(source.position);
  57891. _this.rotation.copyFrom(source.rotation);
  57892. _this.scaling.copyFrom(source.scaling);
  57893. if (source.rotationQuaternion) {
  57894. _this.rotationQuaternion = source.rotationQuaternion.clone();
  57895. }
  57896. _this.infiniteDistance = source.infiniteDistance;
  57897. _this.setPivotMatrix(source.getPivotMatrix());
  57898. _this.refreshBoundingInfo();
  57899. _this._syncSubMeshes();
  57900. return _this;
  57901. }
  57902. /**
  57903. * Returns the string "InstancedMesh".
  57904. */
  57905. InstancedMesh.prototype.getClassName = function () {
  57906. return "InstancedMesh";
  57907. };
  57908. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  57909. // Methods
  57910. get: function () {
  57911. return this._sourceMesh.receiveShadows;
  57912. },
  57913. enumerable: true,
  57914. configurable: true
  57915. });
  57916. Object.defineProperty(InstancedMesh.prototype, "material", {
  57917. get: function () {
  57918. return this._sourceMesh.material;
  57919. },
  57920. enumerable: true,
  57921. configurable: true
  57922. });
  57923. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  57924. get: function () {
  57925. return this._sourceMesh.visibility;
  57926. },
  57927. enumerable: true,
  57928. configurable: true
  57929. });
  57930. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  57931. get: function () {
  57932. return this._sourceMesh.skeleton;
  57933. },
  57934. enumerable: true,
  57935. configurable: true
  57936. });
  57937. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  57938. get: function () {
  57939. return this._sourceMesh.renderingGroupId;
  57940. },
  57941. set: function (value) {
  57942. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  57943. return;
  57944. }
  57945. //no-op with warning
  57946. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  57947. },
  57948. enumerable: true,
  57949. configurable: true
  57950. });
  57951. /**
  57952. * Returns the total number of vertices (integer).
  57953. */
  57954. InstancedMesh.prototype.getTotalVertices = function () {
  57955. return this._sourceMesh.getTotalVertices();
  57956. };
  57957. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  57958. get: function () {
  57959. return this._sourceMesh;
  57960. },
  57961. enumerable: true,
  57962. configurable: true
  57963. });
  57964. /**
  57965. * Is this node ready to be used/rendered
  57966. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  57967. * @return {boolean} is it ready
  57968. */
  57969. InstancedMesh.prototype.isReady = function (completeCheck) {
  57970. if (completeCheck === void 0) { completeCheck = false; }
  57971. return this._sourceMesh.isReady(completeCheck, true);
  57972. };
  57973. /**
  57974. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  57975. */
  57976. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  57977. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  57978. };
  57979. /**
  57980. * Sets the vertex data of the mesh geometry for the requested `kind`.
  57981. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  57982. * The `data` are either a numeric array either a Float32Array.
  57983. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  57984. * 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).
  57985. * Note that a new underlying VertexBuffer object is created each call.
  57986. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  57987. *
  57988. * Possible `kind` values :
  57989. * - BABYLON.VertexBuffer.PositionKind
  57990. * - BABYLON.VertexBuffer.UVKind
  57991. * - BABYLON.VertexBuffer.UV2Kind
  57992. * - BABYLON.VertexBuffer.UV3Kind
  57993. * - BABYLON.VertexBuffer.UV4Kind
  57994. * - BABYLON.VertexBuffer.UV5Kind
  57995. * - BABYLON.VertexBuffer.UV6Kind
  57996. * - BABYLON.VertexBuffer.ColorKind
  57997. * - BABYLON.VertexBuffer.MatricesIndicesKind
  57998. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  57999. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58000. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58001. *
  58002. * Returns the Mesh.
  58003. */
  58004. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58005. if (this.sourceMesh) {
  58006. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58007. }
  58008. return this.sourceMesh;
  58009. };
  58010. /**
  58011. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58012. * If the mesh has no geometry, it is simply returned as it is.
  58013. * The `data` are either a numeric array either a Float32Array.
  58014. * No new underlying VertexBuffer object is created.
  58015. * 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.
  58016. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58017. *
  58018. * Possible `kind` values :
  58019. * - BABYLON.VertexBuffer.PositionKind
  58020. * - BABYLON.VertexBuffer.UVKind
  58021. * - BABYLON.VertexBuffer.UV2Kind
  58022. * - BABYLON.VertexBuffer.UV3Kind
  58023. * - BABYLON.VertexBuffer.UV4Kind
  58024. * - BABYLON.VertexBuffer.UV5Kind
  58025. * - BABYLON.VertexBuffer.UV6Kind
  58026. * - BABYLON.VertexBuffer.ColorKind
  58027. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58028. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58029. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58030. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58031. *
  58032. * Returns the Mesh.
  58033. */
  58034. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58035. if (this.sourceMesh) {
  58036. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58037. }
  58038. return this.sourceMesh;
  58039. };
  58040. /**
  58041. * Sets the mesh indices.
  58042. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58043. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58044. * This method creates a new index buffer each call.
  58045. * Returns the Mesh.
  58046. */
  58047. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58048. if (totalVertices === void 0) { totalVertices = null; }
  58049. if (this.sourceMesh) {
  58050. this.sourceMesh.setIndices(indices, totalVertices);
  58051. }
  58052. return this.sourceMesh;
  58053. };
  58054. /**
  58055. * Boolean : True if the mesh owns the requested kind of data.
  58056. */
  58057. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58058. return this._sourceMesh.isVerticesDataPresent(kind);
  58059. };
  58060. /**
  58061. * Returns an array of indices (IndicesArray).
  58062. */
  58063. InstancedMesh.prototype.getIndices = function () {
  58064. return this._sourceMesh.getIndices();
  58065. };
  58066. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58067. get: function () {
  58068. return this._sourceMesh._positions;
  58069. },
  58070. enumerable: true,
  58071. configurable: true
  58072. });
  58073. /**
  58074. * Sets a new updated BoundingInfo to the mesh.
  58075. * Returns the mesh.
  58076. */
  58077. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58078. var meshBB = this._sourceMesh.getBoundingInfo();
  58079. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58080. this._updateBoundingInfo();
  58081. return this;
  58082. };
  58083. InstancedMesh.prototype._preActivate = function () {
  58084. if (this._currentLOD) {
  58085. this._currentLOD._preActivate();
  58086. }
  58087. return this;
  58088. };
  58089. InstancedMesh.prototype._activate = function (renderId) {
  58090. if (this._currentLOD) {
  58091. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58092. }
  58093. return this;
  58094. };
  58095. /**
  58096. * Returns the current associated LOD AbstractMesh.
  58097. */
  58098. InstancedMesh.prototype.getLOD = function (camera) {
  58099. if (!camera) {
  58100. return this;
  58101. }
  58102. var boundingInfo = this.getBoundingInfo();
  58103. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  58104. if (this._currentLOD === this.sourceMesh) {
  58105. return this;
  58106. }
  58107. return this._currentLOD;
  58108. };
  58109. InstancedMesh.prototype._syncSubMeshes = function () {
  58110. this.releaseSubMeshes();
  58111. if (this._sourceMesh.subMeshes) {
  58112. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  58113. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  58114. }
  58115. }
  58116. return this;
  58117. };
  58118. InstancedMesh.prototype._generatePointsArray = function () {
  58119. return this._sourceMesh._generatePointsArray();
  58120. };
  58121. /**
  58122. * Creates a new InstancedMesh from the current mesh.
  58123. * - name (string) : the cloned mesh name
  58124. * - newParent (optional Node) : the optional Node to parent the clone to.
  58125. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  58126. *
  58127. * Returns the clone.
  58128. */
  58129. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58130. var result = this._sourceMesh.createInstance(name);
  58131. // Deep copy
  58132. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  58133. // Bounding info
  58134. this.refreshBoundingInfo();
  58135. // Parent
  58136. if (newParent) {
  58137. result.parent = newParent;
  58138. }
  58139. if (!doNotCloneChildren) {
  58140. // Children
  58141. for (var index = 0; index < this.getScene().meshes.length; index++) {
  58142. var mesh = this.getScene().meshes[index];
  58143. if (mesh.parent === this) {
  58144. mesh.clone(mesh.name, result);
  58145. }
  58146. }
  58147. }
  58148. result.computeWorldMatrix(true);
  58149. return result;
  58150. };
  58151. /**
  58152. * Disposes the InstancedMesh.
  58153. * Returns nothing.
  58154. */
  58155. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  58156. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  58157. // Remove from mesh
  58158. var index = this._sourceMesh.instances.indexOf(this);
  58159. this._sourceMesh.instances.splice(index, 1);
  58160. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  58161. };
  58162. return InstancedMesh;
  58163. }(BABYLON.AbstractMesh));
  58164. BABYLON.InstancedMesh = InstancedMesh;
  58165. })(BABYLON || (BABYLON = {}));
  58166. //# sourceMappingURL=babylon.instancedMesh.js.map
  58167. var BABYLON;
  58168. (function (BABYLON) {
  58169. var LinesMesh = /** @class */ (function (_super) {
  58170. __extends(LinesMesh, _super);
  58171. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  58172. if (scene === void 0) { scene = null; }
  58173. if (parent === void 0) { parent = null; }
  58174. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  58175. _this.useVertexColor = useVertexColor;
  58176. _this.useVertexAlpha = useVertexAlpha;
  58177. _this.color = new BABYLON.Color3(1, 1, 1);
  58178. _this.alpha = 1;
  58179. if (source) {
  58180. _this.color = source.color.clone();
  58181. _this.alpha = source.alpha;
  58182. _this.useVertexColor = source.useVertexColor;
  58183. _this.useVertexAlpha = source.useVertexAlpha;
  58184. }
  58185. _this._intersectionThreshold = 0.1;
  58186. var defines = [];
  58187. var options = {
  58188. attributes: [BABYLON.VertexBuffer.PositionKind],
  58189. uniforms: ["world", "viewProjection"],
  58190. needAlphaBlending: true,
  58191. defines: defines
  58192. };
  58193. if (useVertexAlpha === false) {
  58194. options.needAlphaBlending = false;
  58195. }
  58196. if (!useVertexColor) {
  58197. options.uniforms.push("color");
  58198. }
  58199. else {
  58200. options.defines.push("#define VERTEXCOLOR");
  58201. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  58202. }
  58203. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  58204. return _this;
  58205. }
  58206. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  58207. /**
  58208. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58209. * This margin is expressed in world space coordinates, so its value may vary.
  58210. * Default value is 0.1
  58211. * @returns the intersection Threshold value.
  58212. */
  58213. get: function () {
  58214. return this._intersectionThreshold;
  58215. },
  58216. /**
  58217. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58218. * This margin is expressed in world space coordinates, so its value may vary.
  58219. * @param value the new threshold to apply
  58220. */
  58221. set: function (value) {
  58222. if (this._intersectionThreshold === value) {
  58223. return;
  58224. }
  58225. this._intersectionThreshold = value;
  58226. if (this.geometry) {
  58227. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  58228. }
  58229. },
  58230. enumerable: true,
  58231. configurable: true
  58232. });
  58233. /**
  58234. * Returns the string "LineMesh"
  58235. */
  58236. LinesMesh.prototype.getClassName = function () {
  58237. return "LinesMesh";
  58238. };
  58239. Object.defineProperty(LinesMesh.prototype, "material", {
  58240. /**
  58241. * @hidden
  58242. */
  58243. get: function () {
  58244. return this._colorShader;
  58245. },
  58246. /**
  58247. * @hidden
  58248. */
  58249. set: function (value) {
  58250. // Do nothing
  58251. },
  58252. enumerable: true,
  58253. configurable: true
  58254. });
  58255. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  58256. /**
  58257. * @hidden
  58258. */
  58259. get: function () {
  58260. return false;
  58261. },
  58262. enumerable: true,
  58263. configurable: true
  58264. });
  58265. LinesMesh.prototype.createInstance = function (name) {
  58266. throw new Error("LinesMeshes do not support createInstance.");
  58267. };
  58268. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  58269. if (!this._geometry) {
  58270. return this;
  58271. }
  58272. // VBOs
  58273. this._geometry._bind(this._colorShader.getEffect());
  58274. // Color
  58275. if (!this.useVertexColor) {
  58276. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  58277. }
  58278. return this;
  58279. };
  58280. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  58281. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  58282. return this;
  58283. }
  58284. var engine = this.getScene().getEngine();
  58285. // Draw order
  58286. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  58287. return this;
  58288. };
  58289. LinesMesh.prototype.dispose = function (doNotRecurse) {
  58290. this._colorShader.dispose();
  58291. _super.prototype.dispose.call(this, doNotRecurse);
  58292. };
  58293. /**
  58294. * Returns a new LineMesh object cloned from the current one.
  58295. */
  58296. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58297. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  58298. };
  58299. return LinesMesh;
  58300. }(BABYLON.Mesh));
  58301. BABYLON.LinesMesh = LinesMesh;
  58302. })(BABYLON || (BABYLON = {}));
  58303. //# sourceMappingURL=babylon.linesMesh.js.map
  58304. var BABYLON;
  58305. (function (BABYLON) {
  58306. /**
  58307. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58308. * The underlying implementation relies on an associative array to ensure the best performances.
  58309. * The value can be anything including 'null' but except 'undefined'
  58310. */
  58311. var StringDictionary = /** @class */ (function () {
  58312. function StringDictionary() {
  58313. this._count = 0;
  58314. this._data = {};
  58315. }
  58316. /**
  58317. * This will clear this dictionary and copy the content from the 'source' one.
  58318. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58319. * @param source the dictionary to take the content from and copy to this dictionary
  58320. */
  58321. StringDictionary.prototype.copyFrom = function (source) {
  58322. var _this = this;
  58323. this.clear();
  58324. source.forEach(function (t, v) { return _this.add(t, v); });
  58325. };
  58326. /**
  58327. * Get a value based from its key
  58328. * @param key the given key to get the matching value from
  58329. * @return the value if found, otherwise undefined is returned
  58330. */
  58331. StringDictionary.prototype.get = function (key) {
  58332. var val = this._data[key];
  58333. if (val !== undefined) {
  58334. return val;
  58335. }
  58336. return undefined;
  58337. };
  58338. /**
  58339. * Get a value from its key or add it if it doesn't exist.
  58340. * This method will ensure you that a given key/data will be present in the dictionary.
  58341. * @param key the given key to get the matching value from
  58342. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58343. * The factory will only be invoked if there's no data for the given key.
  58344. * @return the value corresponding to the key.
  58345. */
  58346. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58347. var val = this.get(key);
  58348. if (val !== undefined) {
  58349. return val;
  58350. }
  58351. val = factory(key);
  58352. if (val) {
  58353. this.add(key, val);
  58354. }
  58355. return val;
  58356. };
  58357. /**
  58358. * Get a value from its key if present in the dictionary otherwise add it
  58359. * @param key the key to get the value from
  58360. * @param val if there's no such key/value pair in the dictionary add it with this value
  58361. * @return the value corresponding to the key
  58362. */
  58363. StringDictionary.prototype.getOrAdd = function (key, val) {
  58364. var curVal = this.get(key);
  58365. if (curVal !== undefined) {
  58366. return curVal;
  58367. }
  58368. this.add(key, val);
  58369. return val;
  58370. };
  58371. /**
  58372. * Check if there's a given key in the dictionary
  58373. * @param key the key to check for
  58374. * @return true if the key is present, false otherwise
  58375. */
  58376. StringDictionary.prototype.contains = function (key) {
  58377. return this._data[key] !== undefined;
  58378. };
  58379. /**
  58380. * Add a new key and its corresponding value
  58381. * @param key the key to add
  58382. * @param value the value corresponding to the key
  58383. * @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
  58384. */
  58385. StringDictionary.prototype.add = function (key, value) {
  58386. if (this._data[key] !== undefined) {
  58387. return false;
  58388. }
  58389. this._data[key] = value;
  58390. ++this._count;
  58391. return true;
  58392. };
  58393. StringDictionary.prototype.set = function (key, value) {
  58394. if (this._data[key] === undefined) {
  58395. return false;
  58396. }
  58397. this._data[key] = value;
  58398. return true;
  58399. };
  58400. /**
  58401. * Get the element of the given key and remove it from the dictionary
  58402. * @param key
  58403. */
  58404. StringDictionary.prototype.getAndRemove = function (key) {
  58405. var val = this.get(key);
  58406. if (val !== undefined) {
  58407. delete this._data[key];
  58408. --this._count;
  58409. return val;
  58410. }
  58411. return null;
  58412. };
  58413. /**
  58414. * Remove a key/value from the dictionary.
  58415. * @param key the key to remove
  58416. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  58417. */
  58418. StringDictionary.prototype.remove = function (key) {
  58419. if (this.contains(key)) {
  58420. delete this._data[key];
  58421. --this._count;
  58422. return true;
  58423. }
  58424. return false;
  58425. };
  58426. /**
  58427. * Clear the whole content of the dictionary
  58428. */
  58429. StringDictionary.prototype.clear = function () {
  58430. this._data = {};
  58431. this._count = 0;
  58432. };
  58433. Object.defineProperty(StringDictionary.prototype, "count", {
  58434. get: function () {
  58435. return this._count;
  58436. },
  58437. enumerable: true,
  58438. configurable: true
  58439. });
  58440. /**
  58441. * Execute a callback on each key/val of the dictionary.
  58442. * Note that you can remove any element in this dictionary in the callback implementation
  58443. * @param callback the callback to execute on a given key/value pair
  58444. */
  58445. StringDictionary.prototype.forEach = function (callback) {
  58446. for (var cur in this._data) {
  58447. var val = this._data[cur];
  58448. callback(cur, val);
  58449. }
  58450. };
  58451. /**
  58452. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58453. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58454. * Note that you can remove any element in this dictionary in the callback implementation
  58455. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58456. */
  58457. StringDictionary.prototype.first = function (callback) {
  58458. for (var cur in this._data) {
  58459. var val = this._data[cur];
  58460. var res = callback(cur, val);
  58461. if (res) {
  58462. return res;
  58463. }
  58464. }
  58465. return null;
  58466. };
  58467. return StringDictionary;
  58468. }());
  58469. BABYLON.StringDictionary = StringDictionary;
  58470. })(BABYLON || (BABYLON = {}));
  58471. //# sourceMappingURL=babylon.stringDictionary.js.map
  58472. var BABYLON;
  58473. (function (BABYLON) {
  58474. var Debug;
  58475. (function (Debug) {
  58476. /**
  58477. * Class used to render a debug view of a given skeleton
  58478. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  58479. */
  58480. var SkeletonViewer = /** @class */ (function () {
  58481. /**
  58482. * Creates a new SkeletonViewer
  58483. * @param skeleton defines the skeleton to render
  58484. * @param mesh defines the mesh attached to the skeleton
  58485. * @param scene defines the hosting scene
  58486. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  58487. * @param renderingGroupId defines the rendering group id to use with the viewer
  58488. */
  58489. function SkeletonViewer(
  58490. /** defines the skeleton to render */
  58491. skeleton,
  58492. /** defines the mesh attached to the skeleton */
  58493. mesh, scene,
  58494. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  58495. autoUpdateBonesMatrices,
  58496. /** defines the rendering group id to use with the viewer */
  58497. renderingGroupId) {
  58498. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58499. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58500. this.skeleton = skeleton;
  58501. this.mesh = mesh;
  58502. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58503. this.renderingGroupId = renderingGroupId;
  58504. /** Gets or sets the color used to render the skeleton */
  58505. this.color = BABYLON.Color3.White();
  58506. this._debugLines = new Array();
  58507. this._isEnabled = false;
  58508. this._scene = scene;
  58509. this.update();
  58510. this._renderFunction = this.update.bind(this);
  58511. }
  58512. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58513. get: function () {
  58514. return this._isEnabled;
  58515. },
  58516. /** Gets or sets a boolean indicating if the viewer is enabled */
  58517. set: function (value) {
  58518. if (this._isEnabled === value) {
  58519. return;
  58520. }
  58521. this._isEnabled = value;
  58522. if (value) {
  58523. this._scene.registerBeforeRender(this._renderFunction);
  58524. }
  58525. else {
  58526. this._scene.unregisterBeforeRender(this._renderFunction);
  58527. }
  58528. },
  58529. enumerable: true,
  58530. configurable: true
  58531. });
  58532. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58533. if (x === void 0) { x = 0; }
  58534. if (y === void 0) { y = 0; }
  58535. if (z === void 0) { z = 0; }
  58536. var tmat = BABYLON.Tmp.Matrix[0];
  58537. var parentBone = bone.getParent();
  58538. tmat.copyFrom(bone.getLocalMatrix());
  58539. if (x !== 0 || y !== 0 || z !== 0) {
  58540. var tmat2 = BABYLON.Tmp.Matrix[1];
  58541. BABYLON.Matrix.IdentityToRef(tmat2);
  58542. tmat2.m[12] = x;
  58543. tmat2.m[13] = y;
  58544. tmat2.m[14] = z;
  58545. tmat2.multiplyToRef(tmat, tmat);
  58546. }
  58547. if (parentBone) {
  58548. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58549. }
  58550. tmat.multiplyToRef(meshMat, tmat);
  58551. position.x = tmat.m[12];
  58552. position.y = tmat.m[13];
  58553. position.z = tmat.m[14];
  58554. };
  58555. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58556. var len = bones.length;
  58557. var meshPos = this.mesh.position;
  58558. for (var i = 0; i < len; i++) {
  58559. var bone = bones[i];
  58560. var points = this._debugLines[i];
  58561. if (!points) {
  58562. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58563. this._debugLines[i] = points;
  58564. }
  58565. this._getBonePosition(points[0], bone, meshMat);
  58566. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58567. points[0].subtractInPlace(meshPos);
  58568. points[1].subtractInPlace(meshPos);
  58569. }
  58570. };
  58571. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58572. var len = bones.length;
  58573. var boneNum = 0;
  58574. var meshPos = this.mesh.position;
  58575. for (var i = len - 1; i >= 0; i--) {
  58576. var childBone = bones[i];
  58577. var parentBone = childBone.getParent();
  58578. if (!parentBone) {
  58579. continue;
  58580. }
  58581. var points = this._debugLines[boneNum];
  58582. if (!points) {
  58583. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58584. this._debugLines[boneNum] = points;
  58585. }
  58586. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  58587. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  58588. points[0].subtractInPlace(meshPos);
  58589. points[1].subtractInPlace(meshPos);
  58590. boneNum++;
  58591. }
  58592. };
  58593. /** Update the viewer to sync with current skeleton state */
  58594. SkeletonViewer.prototype.update = function () {
  58595. if (this.autoUpdateBonesMatrices) {
  58596. this.skeleton.computeAbsoluteTransforms();
  58597. }
  58598. if (this.skeleton.bones[0].length === undefined) {
  58599. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58600. }
  58601. else {
  58602. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58603. }
  58604. if (!this._debugMesh) {
  58605. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  58606. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58607. }
  58608. else {
  58609. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58610. }
  58611. this._debugMesh.position.copyFrom(this.mesh.position);
  58612. this._debugMesh.color = this.color;
  58613. };
  58614. /** Release associated resources */
  58615. SkeletonViewer.prototype.dispose = function () {
  58616. if (this._debugMesh) {
  58617. this.isEnabled = false;
  58618. this._debugMesh.dispose();
  58619. this._debugMesh = null;
  58620. }
  58621. };
  58622. return SkeletonViewer;
  58623. }());
  58624. Debug.SkeletonViewer = SkeletonViewer;
  58625. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58626. })(BABYLON || (BABYLON = {}));
  58627. //# sourceMappingURL=babylon.skeletonViewer.js.map
  58628. /**
  58629. * Module Debug contains the (visual) components to debug a scene correctly
  58630. */
  58631. var BABYLON;
  58632. (function (BABYLON) {
  58633. var Debug;
  58634. (function (Debug) {
  58635. /**
  58636. * The Axes viewer will show 3 axes in a specific point in space
  58637. */
  58638. var AxesViewer = /** @class */ (function () {
  58639. /**
  58640. * Creates a new AxesViewer
  58641. * @param scene defines the hosting scene
  58642. * @param scaleLines defines a number used to scale line length (1 by default)
  58643. */
  58644. function AxesViewer(scene, scaleLines) {
  58645. if (scaleLines === void 0) { scaleLines = 1; }
  58646. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58647. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58648. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58649. /**
  58650. * Gets or sets a number used to scale line length
  58651. */
  58652. this.scaleLines = 1;
  58653. this.scaleLines = scaleLines;
  58654. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  58655. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  58656. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  58657. this._xmesh.renderingGroupId = 2;
  58658. this._ymesh.renderingGroupId = 2;
  58659. this._zmesh.renderingGroupId = 2;
  58660. this._xmesh.material.checkReadyOnlyOnce = true;
  58661. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  58662. this._ymesh.material.checkReadyOnlyOnce = true;
  58663. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  58664. this._zmesh.material.checkReadyOnlyOnce = true;
  58665. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  58666. this.scene = scene;
  58667. }
  58668. /**
  58669. * Force the viewer to update
  58670. * @param position defines the position of the viewer
  58671. * @param xaxis defines the x axis of the viewer
  58672. * @param yaxis defines the y axis of the viewer
  58673. * @param zaxis defines the z axis of the viewer
  58674. */
  58675. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  58676. var scaleLines = this.scaleLines;
  58677. if (this._xmesh) {
  58678. this._xmesh.position.copyFrom(position);
  58679. }
  58680. if (this._ymesh) {
  58681. this._ymesh.position.copyFrom(position);
  58682. }
  58683. if (this._zmesh) {
  58684. this._zmesh.position.copyFrom(position);
  58685. }
  58686. var point2 = this._xline[1];
  58687. point2.x = xaxis.x * scaleLines;
  58688. point2.y = xaxis.y * scaleLines;
  58689. point2.z = xaxis.z * scaleLines;
  58690. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  58691. point2 = this._yline[1];
  58692. point2.x = yaxis.x * scaleLines;
  58693. point2.y = yaxis.y * scaleLines;
  58694. point2.z = yaxis.z * scaleLines;
  58695. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  58696. point2 = this._zline[1];
  58697. point2.x = zaxis.x * scaleLines;
  58698. point2.y = zaxis.y * scaleLines;
  58699. point2.z = zaxis.z * scaleLines;
  58700. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  58701. };
  58702. /** Releases resources */
  58703. AxesViewer.prototype.dispose = function () {
  58704. if (this._xmesh) {
  58705. this._xmesh.dispose();
  58706. }
  58707. if (this._ymesh) {
  58708. this._ymesh.dispose();
  58709. }
  58710. if (this._zmesh) {
  58711. this._zmesh.dispose();
  58712. }
  58713. this._xmesh = null;
  58714. this._ymesh = null;
  58715. this._zmesh = null;
  58716. this.scene = null;
  58717. };
  58718. return AxesViewer;
  58719. }());
  58720. Debug.AxesViewer = AxesViewer;
  58721. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58722. })(BABYLON || (BABYLON = {}));
  58723. //# sourceMappingURL=babylon.axesViewer.js.map
  58724. var BABYLON;
  58725. (function (BABYLON) {
  58726. var Debug;
  58727. (function (Debug) {
  58728. /**
  58729. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  58730. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  58731. */
  58732. var BoneAxesViewer = /** @class */ (function (_super) {
  58733. __extends(BoneAxesViewer, _super);
  58734. /**
  58735. * Creates a new BoneAxesViewer
  58736. * @param scene defines the hosting scene
  58737. * @param bone defines the target bone
  58738. * @param mesh defines the target mesh
  58739. * @param scaleLines defines a scaling factor for line length (1 by default)
  58740. */
  58741. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  58742. if (scaleLines === void 0) { scaleLines = 1; }
  58743. var _this = _super.call(this, scene, scaleLines) || this;
  58744. /** Gets current position */
  58745. _this.pos = BABYLON.Vector3.Zero();
  58746. /** Gets direction of X axis */
  58747. _this.xaxis = BABYLON.Vector3.Zero();
  58748. /** Gets direction of Y axis */
  58749. _this.yaxis = BABYLON.Vector3.Zero();
  58750. /** Gets direction of Z axis */
  58751. _this.zaxis = BABYLON.Vector3.Zero();
  58752. _this.mesh = mesh;
  58753. _this.bone = bone;
  58754. return _this;
  58755. }
  58756. /**
  58757. * Force the viewer to update
  58758. */
  58759. BoneAxesViewer.prototype.update = function () {
  58760. if (!this.mesh || !this.bone) {
  58761. return;
  58762. }
  58763. var bone = this.bone;
  58764. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  58765. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  58766. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  58767. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  58768. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  58769. };
  58770. /** Releases resources */
  58771. BoneAxesViewer.prototype.dispose = function () {
  58772. if (this.mesh) {
  58773. this.mesh = null;
  58774. this.bone = null;
  58775. _super.prototype.dispose.call(this);
  58776. }
  58777. };
  58778. return BoneAxesViewer;
  58779. }(Debug.AxesViewer));
  58780. Debug.BoneAxesViewer = BoneAxesViewer;
  58781. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58782. })(BABYLON || (BABYLON = {}));
  58783. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  58784. var BABYLON;
  58785. (function (BABYLON) {
  58786. var RayHelper = /** @class */ (function () {
  58787. function RayHelper(ray) {
  58788. this.ray = ray;
  58789. }
  58790. RayHelper.CreateAndShow = function (ray, scene, color) {
  58791. var helper = new RayHelper(ray);
  58792. helper.show(scene, color);
  58793. return helper;
  58794. };
  58795. RayHelper.prototype.show = function (scene, color) {
  58796. if (!this._renderFunction && this.ray) {
  58797. var ray = this.ray;
  58798. this._renderFunction = this._render.bind(this);
  58799. this._scene = scene;
  58800. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  58801. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  58802. if (this._renderFunction) {
  58803. this._scene.registerBeforeRender(this._renderFunction);
  58804. }
  58805. }
  58806. if (color && this._renderLine) {
  58807. this._renderLine.color.copyFrom(color);
  58808. }
  58809. };
  58810. RayHelper.prototype.hide = function () {
  58811. if (this._renderFunction && this._scene) {
  58812. this._scene.unregisterBeforeRender(this._renderFunction);
  58813. this._scene = null;
  58814. this._renderFunction = null;
  58815. if (this._renderLine) {
  58816. this._renderLine.dispose();
  58817. this._renderLine = null;
  58818. }
  58819. this._renderPoints = [];
  58820. }
  58821. };
  58822. RayHelper.prototype._render = function () {
  58823. var ray = this.ray;
  58824. if (!ray) {
  58825. return;
  58826. }
  58827. var point = this._renderPoints[1];
  58828. var len = Math.min(ray.length, 1000000);
  58829. point.copyFrom(ray.direction);
  58830. point.scaleInPlace(len);
  58831. point.addInPlace(ray.origin);
  58832. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  58833. };
  58834. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  58835. this._attachedToMesh = mesh;
  58836. var ray = this.ray;
  58837. if (!ray) {
  58838. return;
  58839. }
  58840. if (!ray.direction) {
  58841. ray.direction = BABYLON.Vector3.Zero();
  58842. }
  58843. if (!ray.origin) {
  58844. ray.origin = BABYLON.Vector3.Zero();
  58845. }
  58846. if (length) {
  58847. ray.length = length;
  58848. }
  58849. if (!meshSpaceOrigin) {
  58850. meshSpaceOrigin = BABYLON.Vector3.Zero();
  58851. }
  58852. if (!meshSpaceDirection) {
  58853. // -1 so that this will work with Mesh.lookAt
  58854. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  58855. }
  58856. if (!this._meshSpaceDirection) {
  58857. this._meshSpaceDirection = meshSpaceDirection.clone();
  58858. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  58859. }
  58860. else {
  58861. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  58862. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  58863. }
  58864. if (!this._updateToMeshFunction) {
  58865. this._updateToMeshFunction = this._updateToMesh.bind(this);
  58866. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  58867. }
  58868. this._updateToMesh();
  58869. };
  58870. RayHelper.prototype.detachFromMesh = function () {
  58871. if (this._attachedToMesh) {
  58872. if (this._updateToMeshFunction) {
  58873. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  58874. }
  58875. this._attachedToMesh = null;
  58876. this._updateToMeshFunction = null;
  58877. }
  58878. };
  58879. RayHelper.prototype._updateToMesh = function () {
  58880. var ray = this.ray;
  58881. if (!this._attachedToMesh || !ray) {
  58882. return;
  58883. }
  58884. if (this._attachedToMesh._isDisposed) {
  58885. this.detachFromMesh();
  58886. return;
  58887. }
  58888. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  58889. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  58890. };
  58891. RayHelper.prototype.dispose = function () {
  58892. this.hide();
  58893. this.detachFromMesh();
  58894. this.ray = null;
  58895. };
  58896. return RayHelper;
  58897. }());
  58898. BABYLON.RayHelper = RayHelper;
  58899. })(BABYLON || (BABYLON = {}));
  58900. //# sourceMappingURL=babylon.rayHelper.js.map
  58901. var BABYLON;
  58902. (function (BABYLON) {
  58903. // load the inspector using require, if not present in the global namespace.
  58904. var DebugLayer = /** @class */ (function () {
  58905. function DebugLayer(scene) {
  58906. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  58907. this.onPropertyChangedObservable = new BABYLON.Observable();
  58908. this._scene = scene;
  58909. }
  58910. /** Creates the inspector window. */
  58911. DebugLayer.prototype._createInspector = function (config) {
  58912. if (config === void 0) { config = {}; }
  58913. var popup = config.popup || false;
  58914. var initialTab = config.initialTab || 0;
  58915. var parentElement = config.parentElement || null;
  58916. if (!this._inspector) {
  58917. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  58918. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  58919. } // else nothing to do as instance is already created
  58920. };
  58921. DebugLayer.prototype.isVisible = function () {
  58922. if (!this._inspector) {
  58923. return false;
  58924. }
  58925. return true;
  58926. };
  58927. DebugLayer.prototype.hide = function () {
  58928. if (this._inspector) {
  58929. try {
  58930. this._inspector.dispose();
  58931. }
  58932. catch (e) {
  58933. // If the inspector has been removed directly from the inspector tool
  58934. }
  58935. this.onPropertyChangedObservable.clear();
  58936. this._inspector = null;
  58937. }
  58938. };
  58939. /**
  58940. *
  58941. * Launch the debugLayer.
  58942. *
  58943. * initialTab:
  58944. * | Value | Tab Name |
  58945. * | --- | --- |
  58946. * | 0 | Scene |
  58947. * | 1 | Console |
  58948. * | 2 | Stats |
  58949. * | 3 | Textures |
  58950. * | 4 | Mesh |
  58951. * | 5 | Light |
  58952. * | 6 | Material |
  58953. * | 7 | GLTF |
  58954. * | 8 | GUI |
  58955. * | 9 | Physics |
  58956. * | 10 | Camera |
  58957. * | 11 | Audio |
  58958. *
  58959. */
  58960. DebugLayer.prototype.show = function (config) {
  58961. if (config === void 0) { config = {}; }
  58962. if (typeof this.BJSINSPECTOR == 'undefined') {
  58963. // Load inspector and add it to the DOM
  58964. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  58965. }
  58966. else {
  58967. // Otherwise creates the inspector
  58968. this._createInspector(config);
  58969. }
  58970. };
  58971. /**
  58972. * Gets the active tab
  58973. * @return the index of the active tab or -1 if the inspector is hidden
  58974. */
  58975. DebugLayer.prototype.getActiveTab = function () {
  58976. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  58977. };
  58978. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  58979. return DebugLayer;
  58980. }());
  58981. BABYLON.DebugLayer = DebugLayer;
  58982. })(BABYLON || (BABYLON = {}));
  58983. //# sourceMappingURL=babylon.debugLayer.js.map
  58984. var BABYLON;
  58985. (function (BABYLON) {
  58986. var Debug;
  58987. (function (Debug) {
  58988. /**
  58989. * Used to show the physics impostor around the specific mesh
  58990. */
  58991. var PhysicsViewer = /** @class */ (function () {
  58992. /**
  58993. * Creates a new PhysicsViewer
  58994. * @param scene defines the hosting scene
  58995. */
  58996. function PhysicsViewer(scene) {
  58997. /** @hidden */
  58998. this._impostors = [];
  58999. /** @hidden */
  59000. this._meshes = [];
  59001. /** @hidden */
  59002. this._numMeshes = 0;
  59003. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59004. var physicEngine = this._scene.getPhysicsEngine();
  59005. if (physicEngine) {
  59006. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  59007. }
  59008. }
  59009. /** @hidden */
  59010. PhysicsViewer.prototype._updateDebugMeshes = function () {
  59011. var plugin = this._physicsEnginePlugin;
  59012. for (var i = 0; i < this._numMeshes; i++) {
  59013. var impostor = this._impostors[i];
  59014. if (!impostor) {
  59015. continue;
  59016. }
  59017. if (impostor.isDisposed) {
  59018. this.hideImpostor(this._impostors[i--]);
  59019. }
  59020. else {
  59021. var mesh = this._meshes[i];
  59022. if (mesh && plugin) {
  59023. plugin.syncMeshWithImpostor(mesh, impostor);
  59024. }
  59025. }
  59026. }
  59027. };
  59028. /**
  59029. * Renders a specified physic impostor
  59030. * @param impostor defines the impostor to render
  59031. */
  59032. PhysicsViewer.prototype.showImpostor = function (impostor) {
  59033. if (!this._scene) {
  59034. return;
  59035. }
  59036. for (var i = 0; i < this._numMeshes; i++) {
  59037. if (this._impostors[i] == impostor) {
  59038. return;
  59039. }
  59040. }
  59041. var debugMesh = this._getDebugMesh(impostor, this._scene);
  59042. if (debugMesh) {
  59043. this._impostors[this._numMeshes] = impostor;
  59044. this._meshes[this._numMeshes] = debugMesh;
  59045. if (this._numMeshes === 0) {
  59046. this._renderFunction = this._updateDebugMeshes.bind(this);
  59047. this._scene.registerBeforeRender(this._renderFunction);
  59048. }
  59049. this._numMeshes++;
  59050. }
  59051. };
  59052. /**
  59053. * Hides a specified physic impostor
  59054. * @param impostor defines the impostor to hide
  59055. */
  59056. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  59057. if (!impostor || !this._scene) {
  59058. return;
  59059. }
  59060. var removed = false;
  59061. for (var i = 0; i < this._numMeshes; i++) {
  59062. if (this._impostors[i] == impostor) {
  59063. var mesh = this._meshes[i];
  59064. if (!mesh) {
  59065. continue;
  59066. }
  59067. this._scene.removeMesh(mesh);
  59068. mesh.dispose();
  59069. this._numMeshes--;
  59070. if (this._numMeshes > 0) {
  59071. this._meshes[i] = this._meshes[this._numMeshes];
  59072. this._impostors[i] = this._impostors[this._numMeshes];
  59073. this._meshes[this._numMeshes] = null;
  59074. this._impostors[this._numMeshes] = null;
  59075. }
  59076. else {
  59077. this._meshes[0] = null;
  59078. this._impostors[0] = null;
  59079. }
  59080. removed = true;
  59081. break;
  59082. }
  59083. }
  59084. if (removed && this._numMeshes === 0) {
  59085. this._scene.unregisterBeforeRender(this._renderFunction);
  59086. }
  59087. };
  59088. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  59089. if (!this._debugMaterial) {
  59090. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59091. this._debugMaterial.wireframe = true;
  59092. }
  59093. return this._debugMaterial;
  59094. };
  59095. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  59096. if (!this._debugBoxMesh) {
  59097. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59098. this._debugBoxMesh.renderingGroupId = 1;
  59099. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59100. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59101. scene.removeMesh(this._debugBoxMesh);
  59102. }
  59103. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59104. };
  59105. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  59106. if (!this._debugSphereMesh) {
  59107. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59108. this._debugSphereMesh.renderingGroupId = 1;
  59109. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59110. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59111. scene.removeMesh(this._debugSphereMesh);
  59112. }
  59113. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59114. };
  59115. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  59116. var mesh = null;
  59117. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  59118. mesh = this._getDebugBoxMesh(scene);
  59119. impostor.getBoxSizeToRef(mesh.scaling);
  59120. }
  59121. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  59122. mesh = this._getDebugSphereMesh(scene);
  59123. var radius = impostor.getRadius();
  59124. mesh.scaling.x = radius * 2;
  59125. mesh.scaling.y = radius * 2;
  59126. mesh.scaling.z = radius * 2;
  59127. }
  59128. return mesh;
  59129. };
  59130. /** Releases all resources */
  59131. PhysicsViewer.prototype.dispose = function () {
  59132. for (var i = 0; i < this._numMeshes; i++) {
  59133. this.hideImpostor(this._impostors[i]);
  59134. }
  59135. if (this._debugBoxMesh) {
  59136. this._debugBoxMesh.dispose();
  59137. }
  59138. if (this._debugSphereMesh) {
  59139. this._debugSphereMesh.dispose();
  59140. }
  59141. if (this._debugMaterial) {
  59142. this._debugMaterial.dispose();
  59143. }
  59144. this._impostors.length = 0;
  59145. this._scene = null;
  59146. this._physicsEnginePlugin = null;
  59147. };
  59148. return PhysicsViewer;
  59149. }());
  59150. Debug.PhysicsViewer = PhysicsViewer;
  59151. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59152. })(BABYLON || (BABYLON = {}));
  59153. //# sourceMappingURL=babylon.physicsViewer.js.map
  59154. var BABYLON;
  59155. (function (BABYLON) {
  59156. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  59157. get: function () {
  59158. return this._forceShowBoundingBoxes || false;
  59159. },
  59160. set: function (value) {
  59161. this._forceShowBoundingBoxes = value;
  59162. // Lazyly creates a BB renderer if needed.
  59163. if (value) {
  59164. this.getBoundingBoxRenderer();
  59165. }
  59166. },
  59167. enumerable: true,
  59168. configurable: true
  59169. });
  59170. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  59171. if (!this._boundingBoxRenderer) {
  59172. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  59173. }
  59174. return this._boundingBoxRenderer;
  59175. };
  59176. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  59177. get: function () {
  59178. return this._showBoundingBox || false;
  59179. },
  59180. set: function (value) {
  59181. this._showBoundingBox = value;
  59182. // Lazyly creates a BB renderer if needed.
  59183. if (value) {
  59184. this.getScene().getBoundingBoxRenderer();
  59185. }
  59186. },
  59187. enumerable: true,
  59188. configurable: true
  59189. });
  59190. var BoundingBoxRenderer = /** @class */ (function () {
  59191. function BoundingBoxRenderer(scene) {
  59192. /**
  59193. * The component name helpfull to identify the component in the list of scene components.
  59194. */
  59195. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  59196. this.frontColor = new BABYLON.Color3(1, 1, 1);
  59197. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  59198. this.showBackLines = true;
  59199. this.renderList = new BABYLON.SmartArray(32);
  59200. this._vertexBuffers = {};
  59201. this.scene = scene;
  59202. scene._addComponent(this);
  59203. }
  59204. /**
  59205. * Registers the component in a given scene
  59206. */
  59207. BoundingBoxRenderer.prototype.register = function () {
  59208. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  59209. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  59210. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  59211. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  59212. };
  59213. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  59214. if (mesh.showSubMeshesBoundingBox) {
  59215. var boundingInfo = subMesh.getBoundingInfo();
  59216. if (boundingInfo !== null && boundingInfo !== undefined) {
  59217. this.renderList.push(boundingInfo.boundingBox);
  59218. }
  59219. }
  59220. };
  59221. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  59222. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  59223. var boundingInfo = sourceMesh.getBoundingInfo();
  59224. this.renderList.push(boundingInfo.boundingBox);
  59225. }
  59226. };
  59227. BoundingBoxRenderer.prototype._prepareRessources = function () {
  59228. if (this._colorShader) {
  59229. return;
  59230. }
  59231. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  59232. attributes: [BABYLON.VertexBuffer.PositionKind],
  59233. uniforms: ["world", "viewProjection", "color"]
  59234. });
  59235. var engine = this.scene.getEngine();
  59236. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  59237. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  59238. this._createIndexBuffer();
  59239. };
  59240. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  59241. var engine = this.scene.getEngine();
  59242. 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]);
  59243. };
  59244. /**
  59245. * Rebuilds the elements related to this component in case of
  59246. * context lost for instance.
  59247. */
  59248. BoundingBoxRenderer.prototype.rebuild = function () {
  59249. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59250. if (vb) {
  59251. vb._rebuild();
  59252. }
  59253. this._createIndexBuffer();
  59254. };
  59255. BoundingBoxRenderer.prototype.reset = function () {
  59256. this.renderList.reset();
  59257. };
  59258. BoundingBoxRenderer.prototype.render = function () {
  59259. if (this.renderList.length === 0) {
  59260. return;
  59261. }
  59262. this._prepareRessources();
  59263. if (!this._colorShader.isReady()) {
  59264. return;
  59265. }
  59266. var engine = this.scene.getEngine();
  59267. engine.setDepthWrite(false);
  59268. this._colorShader._preBind();
  59269. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  59270. var boundingBox = this.renderList.data[boundingBoxIndex];
  59271. var min = boundingBox.minimum;
  59272. var max = boundingBox.maximum;
  59273. var diff = max.subtract(min);
  59274. var median = min.add(diff.scale(0.5));
  59275. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59276. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59277. .multiply(boundingBox.getWorldMatrix());
  59278. // VBOs
  59279. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59280. if (this.showBackLines) {
  59281. // Back
  59282. engine.setDepthFunctionToGreaterOrEqual();
  59283. this.scene.resetCachedMaterial();
  59284. this._colorShader.setColor4("color", this.backColor.toColor4());
  59285. this._colorShader.bind(worldMatrix);
  59286. // Draw order
  59287. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59288. }
  59289. // Front
  59290. engine.setDepthFunctionToLess();
  59291. this.scene.resetCachedMaterial();
  59292. this._colorShader.setColor4("color", this.frontColor.toColor4());
  59293. this._colorShader.bind(worldMatrix);
  59294. // Draw order
  59295. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59296. }
  59297. this._colorShader.unbind();
  59298. engine.setDepthFunctionToLessOrEqual();
  59299. engine.setDepthWrite(true);
  59300. };
  59301. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  59302. this._prepareRessources();
  59303. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  59304. return;
  59305. }
  59306. var engine = this.scene.getEngine();
  59307. engine.setDepthWrite(false);
  59308. engine.setColorWrite(false);
  59309. this._colorShader._preBind();
  59310. var boundingBox = mesh._boundingInfo.boundingBox;
  59311. var min = boundingBox.minimum;
  59312. var max = boundingBox.maximum;
  59313. var diff = max.subtract(min);
  59314. var median = min.add(diff.scale(0.5));
  59315. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59316. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59317. .multiply(boundingBox.getWorldMatrix());
  59318. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59319. engine.setDepthFunctionToLess();
  59320. this.scene.resetCachedMaterial();
  59321. this._colorShader.bind(worldMatrix);
  59322. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59323. this._colorShader.unbind();
  59324. engine.setDepthFunctionToLessOrEqual();
  59325. engine.setDepthWrite(true);
  59326. engine.setColorWrite(true);
  59327. };
  59328. BoundingBoxRenderer.prototype.dispose = function () {
  59329. if (!this._colorShader) {
  59330. return;
  59331. }
  59332. this.renderList.dispose();
  59333. this._colorShader.dispose();
  59334. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59335. if (buffer) {
  59336. buffer.dispose();
  59337. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59338. }
  59339. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  59340. };
  59341. return BoundingBoxRenderer;
  59342. }());
  59343. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  59344. })(BABYLON || (BABYLON = {}));
  59345. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  59346. var BABYLON;
  59347. (function (BABYLON) {
  59348. BABYLON.Engine.prototype.createTransformFeedback = function () {
  59349. return this._gl.createTransformFeedback();
  59350. };
  59351. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  59352. this._gl.deleteTransformFeedback(value);
  59353. };
  59354. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  59355. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  59356. };
  59357. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  59358. if (usePoints === void 0) { usePoints = true; }
  59359. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  59360. };
  59361. BABYLON.Engine.prototype.endTransformFeedback = function () {
  59362. this._gl.endTransformFeedback();
  59363. };
  59364. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  59365. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  59366. };
  59367. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  59368. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  59369. };
  59370. })(BABYLON || (BABYLON = {}));
  59371. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  59372. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59373. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59374. s = arguments[i];
  59375. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59376. t[p] = s[p];
  59377. }
  59378. return t;
  59379. };
  59380. var BABYLON;
  59381. (function (BABYLON) {
  59382. /**
  59383. * This represents a GPU particle system in Babylon
  59384. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  59385. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  59386. */
  59387. var GPUParticleSystem = /** @class */ (function () {
  59388. /**
  59389. * Instantiates a GPU particle system.
  59390. * 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.
  59391. * @param name The name of the particle system
  59392. * @param options The options used to create the system
  59393. * @param scene The scene the particle system belongs to
  59394. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  59395. */
  59396. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  59397. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59398. /**
  59399. * The emitter represents the Mesh or position we are attaching the particle system to.
  59400. */
  59401. this.emitter = null;
  59402. /**
  59403. * The rendering group used by the Particle system to chose when to render.
  59404. */
  59405. this.renderingGroupId = 0;
  59406. /**
  59407. * The layer mask we are rendering the particles through.
  59408. */
  59409. this.layerMask = 0x0FFFFFFF;
  59410. this._accumulatedCount = 0;
  59411. this._targetIndex = 0;
  59412. this._currentRenderId = -1;
  59413. this._started = false;
  59414. this._stopped = false;
  59415. this._timeDelta = 0;
  59416. this._attributesStrideSize = 21;
  59417. this._actualFrame = 0;
  59418. this._rawTextureWidth = 256;
  59419. /**
  59420. * List of animations used by the particle system.
  59421. */
  59422. this.animations = [];
  59423. /**
  59424. * An event triggered when the system is disposed.
  59425. */
  59426. this.onDisposeObservable = new BABYLON.Observable();
  59427. /**
  59428. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  59429. */
  59430. this.updateSpeed = 0.01;
  59431. /**
  59432. * The amount of time the particle system is running (depends of the overall update speed).
  59433. */
  59434. this.targetStopDuration = 0;
  59435. /**
  59436. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  59437. */
  59438. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  59439. /**
  59440. * Minimum life time of emitting particles.
  59441. */
  59442. this.minLifeTime = 1;
  59443. /**
  59444. * Maximum life time of emitting particles.
  59445. */
  59446. this.maxLifeTime = 1;
  59447. /**
  59448. * Minimum Size of emitting particles.
  59449. */
  59450. this.minSize = 1;
  59451. /**
  59452. * Maximum Size of emitting particles.
  59453. */
  59454. this.maxSize = 1;
  59455. /**
  59456. * Minimum scale of emitting particles on X axis.
  59457. */
  59458. this.minScaleX = 1;
  59459. /**
  59460. * Maximum scale of emitting particles on X axis.
  59461. */
  59462. this.maxScaleX = 1;
  59463. /**
  59464. * Minimum scale of emitting particles on Y axis.
  59465. */
  59466. this.minScaleY = 1;
  59467. /**
  59468. * Maximum scale of emitting particles on Y axis.
  59469. */
  59470. this.maxScaleY = 1;
  59471. /**
  59472. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59473. */
  59474. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59475. /**
  59476. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59477. */
  59478. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59479. /**
  59480. * Color the particle will have at the end of its lifetime.
  59481. */
  59482. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  59483. /**
  59484. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  59485. */
  59486. this.emitRate = 100;
  59487. /**
  59488. * You can use gravity if you want to give an orientation to your particles.
  59489. */
  59490. this.gravity = BABYLON.Vector3.Zero();
  59491. /**
  59492. * Minimum power of emitting particles.
  59493. */
  59494. this.minEmitPower = 1;
  59495. /**
  59496. * Maximum power of emitting particles.
  59497. */
  59498. this.maxEmitPower = 1;
  59499. /**
  59500. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  59501. */
  59502. this.minAngularSpeed = 0;
  59503. /**
  59504. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  59505. */
  59506. this.maxAngularSpeed = 0;
  59507. /**
  59508. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59509. * to override the particles.
  59510. */
  59511. this.forceDepthWrite = false;
  59512. this._preWarmDone = false;
  59513. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  59514. this.preWarmCycles = 0;
  59515. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  59516. this.preWarmStepOffset = 1;
  59517. /**
  59518. * Gets or sets the minimal initial rotation in radians.
  59519. */
  59520. this.minInitialRotation = 0;
  59521. /**
  59522. * Gets or sets the maximal initial rotation in radians.
  59523. */
  59524. this.maxInitialRotation = 0;
  59525. /**
  59526. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  59527. */
  59528. this.spriteCellChangeSpeed = 1;
  59529. /**
  59530. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  59531. */
  59532. this.startSpriteCellID = 0;
  59533. /**
  59534. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  59535. */
  59536. this.endSpriteCellID = 0;
  59537. /**
  59538. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  59539. */
  59540. this.spriteCellWidth = 0;
  59541. /**
  59542. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  59543. */
  59544. this.spriteCellHeight = 0;
  59545. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  59546. this.translationPivot = new BABYLON.Vector2(0, 0);
  59547. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  59548. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  59549. /**
  59550. * Gets or sets the billboard mode to use when isBillboardBased = true.
  59551. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  59552. */
  59553. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59554. this._isBillboardBased = true;
  59555. this._colorGradients = null;
  59556. this._angularSpeedGradients = null;
  59557. this._sizeGradients = null;
  59558. this._velocityGradients = null;
  59559. this.id = name;
  59560. this.name = name;
  59561. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59562. this._engine = this._scene.getEngine();
  59563. if (!options.randomTextureSize) {
  59564. delete options.randomTextureSize;
  59565. }
  59566. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  59567. var optionsAsNumber = options;
  59568. if (isFinite(optionsAsNumber)) {
  59569. fullOptions.capacity = optionsAsNumber;
  59570. }
  59571. this._capacity = fullOptions.capacity;
  59572. this._activeCount = fullOptions.capacity;
  59573. this._currentActiveCount = 0;
  59574. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59575. this._scene.particleSystems.push(this);
  59576. this._updateEffectOptions = {
  59577. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  59578. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  59579. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  59580. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  59581. uniformBuffersNames: [],
  59582. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  59583. defines: "",
  59584. fallbacks: null,
  59585. onCompiled: null,
  59586. onError: null,
  59587. indexParameters: null,
  59588. maxSimultaneousLights: 0,
  59589. transformFeedbackVaryings: []
  59590. };
  59591. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59592. // Random data
  59593. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  59594. var d = [];
  59595. for (var i = 0; i < maxTextureSize; ++i) {
  59596. d.push(Math.random());
  59597. d.push(Math.random());
  59598. d.push(Math.random());
  59599. d.push(Math.random());
  59600. }
  59601. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  59602. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59603. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59604. d = [];
  59605. for (var i = 0; i < maxTextureSize; ++i) {
  59606. d.push(Math.random());
  59607. d.push(Math.random());
  59608. d.push(Math.random());
  59609. d.push(Math.random());
  59610. }
  59611. this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  59612. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59613. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59614. this._randomTextureSize = maxTextureSize;
  59615. }
  59616. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  59617. /**
  59618. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  59619. */
  59620. get: function () {
  59621. if (!BABYLON.Engine.LastCreatedEngine) {
  59622. return false;
  59623. }
  59624. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  59625. },
  59626. enumerable: true,
  59627. configurable: true
  59628. });
  59629. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  59630. /**
  59631. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59632. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59633. */
  59634. get: function () {
  59635. if (this.particleEmitterType.direction1) {
  59636. return this.particleEmitterType.direction1;
  59637. }
  59638. return BABYLON.Vector3.Zero();
  59639. },
  59640. set: function (value) {
  59641. if (this.particleEmitterType.direction1) {
  59642. this.particleEmitterType.direction1 = value;
  59643. }
  59644. },
  59645. enumerable: true,
  59646. configurable: true
  59647. });
  59648. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  59649. /**
  59650. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59651. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59652. */
  59653. get: function () {
  59654. if (this.particleEmitterType.direction2) {
  59655. return this.particleEmitterType.direction2;
  59656. }
  59657. return BABYLON.Vector3.Zero();
  59658. },
  59659. set: function (value) {
  59660. if (this.particleEmitterType.direction2) {
  59661. this.particleEmitterType.direction2 = value;
  59662. }
  59663. },
  59664. enumerable: true,
  59665. configurable: true
  59666. });
  59667. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  59668. /**
  59669. * 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.
  59670. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59671. */
  59672. get: function () {
  59673. if (this.particleEmitterType.minEmitBox) {
  59674. return this.particleEmitterType.minEmitBox;
  59675. }
  59676. return BABYLON.Vector3.Zero();
  59677. },
  59678. set: function (value) {
  59679. if (this.particleEmitterType.minEmitBox) {
  59680. this.particleEmitterType.minEmitBox = value;
  59681. }
  59682. },
  59683. enumerable: true,
  59684. configurable: true
  59685. });
  59686. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  59687. /**
  59688. * 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.
  59689. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59690. */
  59691. get: function () {
  59692. if (this.particleEmitterType.maxEmitBox) {
  59693. return this.particleEmitterType.maxEmitBox;
  59694. }
  59695. return BABYLON.Vector3.Zero();
  59696. },
  59697. set: function (value) {
  59698. if (this.particleEmitterType.maxEmitBox) {
  59699. this.particleEmitterType.maxEmitBox = value;
  59700. }
  59701. },
  59702. enumerable: true,
  59703. configurable: true
  59704. });
  59705. /**
  59706. * Gets the maximum number of particles active at the same time.
  59707. * @returns The max number of active particles.
  59708. */
  59709. GPUParticleSystem.prototype.getCapacity = function () {
  59710. return this._capacity;
  59711. };
  59712. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  59713. /**
  59714. * Gets or set the number of active particles
  59715. */
  59716. get: function () {
  59717. return this._activeCount;
  59718. },
  59719. set: function (value) {
  59720. this._activeCount = Math.min(value, this._capacity);
  59721. },
  59722. enumerable: true,
  59723. configurable: true
  59724. });
  59725. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  59726. /**
  59727. * Gets whether an animation sprite sheet is enabled or not on the particle system
  59728. */
  59729. get: function () {
  59730. return this._isAnimationSheetEnabled;
  59731. },
  59732. enumerable: true,
  59733. configurable: true
  59734. });
  59735. /**
  59736. * Is this system ready to be used/rendered
  59737. * @return true if the system is ready
  59738. */
  59739. GPUParticleSystem.prototype.isReady = function () {
  59740. if (!this._updateEffect) {
  59741. this._recreateUpdateEffect();
  59742. this._recreateRenderEffect();
  59743. return false;
  59744. }
  59745. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59746. return false;
  59747. }
  59748. return true;
  59749. };
  59750. /**
  59751. * Gets Wether the system has been started.
  59752. * @returns True if it has been started, otherwise false.
  59753. */
  59754. GPUParticleSystem.prototype.isStarted = function () {
  59755. return this._started;
  59756. };
  59757. /**
  59758. * Starts the particle system and begins to emit
  59759. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  59760. */
  59761. GPUParticleSystem.prototype.start = function (delay) {
  59762. var _this = this;
  59763. if (delay === void 0) { delay = 0; }
  59764. if (delay) {
  59765. setTimeout(function () {
  59766. _this.start(0);
  59767. }, delay);
  59768. return;
  59769. }
  59770. this._started = true;
  59771. this._stopped = false;
  59772. this._preWarmDone = false;
  59773. };
  59774. /**
  59775. * Stops the particle system.
  59776. */
  59777. GPUParticleSystem.prototype.stop = function () {
  59778. this._stopped = true;
  59779. };
  59780. /**
  59781. * Remove all active particles
  59782. */
  59783. GPUParticleSystem.prototype.reset = function () {
  59784. this._releaseBuffers();
  59785. this._releaseVAOs();
  59786. this._currentActiveCount = 0;
  59787. this._targetIndex = 0;
  59788. };
  59789. /**
  59790. * Returns the string "GPUParticleSystem"
  59791. * @returns a string containing the class name
  59792. */
  59793. GPUParticleSystem.prototype.getClassName = function () {
  59794. return "GPUParticleSystem";
  59795. };
  59796. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  59797. /**
  59798. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  59799. */
  59800. get: function () {
  59801. return this._isBillboardBased;
  59802. },
  59803. set: function (value) {
  59804. if (this._isBillboardBased === value) {
  59805. return;
  59806. }
  59807. this._isBillboardBased = value;
  59808. this._releaseBuffers();
  59809. },
  59810. enumerable: true,
  59811. configurable: true
  59812. });
  59813. /**
  59814. * Gets the current list of color gradients.
  59815. * You must use addColorGradient and removeColorGradient to udpate this list
  59816. * @returns the list of color gradients
  59817. */
  59818. GPUParticleSystem.prototype.getColorGradients = function () {
  59819. return this._colorGradients;
  59820. };
  59821. /**
  59822. * Gets the current list of size gradients.
  59823. * You must use addSizeGradient and removeSizeGradient to udpate this list
  59824. * @returns the list of size gradients
  59825. */
  59826. GPUParticleSystem.prototype.getSizeGradients = function () {
  59827. return this._sizeGradients;
  59828. };
  59829. /**
  59830. * Gets the current list of angular speed gradients.
  59831. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  59832. * @returns the list of angular speed gradients
  59833. */
  59834. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  59835. return this._angularSpeedGradients;
  59836. };
  59837. /**
  59838. * Gets the current list of velocity gradients.
  59839. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  59840. * @returns the list of angular speed gradients
  59841. */
  59842. GPUParticleSystem.prototype.getVelocityGradients = function () {
  59843. return this._velocityGradients;
  59844. };
  59845. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  59846. if (!gradients) {
  59847. return this;
  59848. }
  59849. var index = 0;
  59850. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  59851. var valueGradient = gradients_1[_i];
  59852. if (valueGradient.gradient === gradient) {
  59853. gradients.splice(index, 1);
  59854. break;
  59855. }
  59856. index++;
  59857. }
  59858. if (texture) {
  59859. texture.dispose();
  59860. }
  59861. this._releaseBuffers();
  59862. return this;
  59863. };
  59864. /**
  59865. * Adds a new color gradient
  59866. * @param gradient defines the gradient to use (between 0 and 1)
  59867. * @param color defines the color to affect to the specified gradient
  59868. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59869. * @returns the current particle system
  59870. */
  59871. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59872. if (!this._colorGradients) {
  59873. this._colorGradients = [];
  59874. }
  59875. var colorGradient = new BABYLON.ColorGradient();
  59876. colorGradient.gradient = gradient;
  59877. colorGradient.color1 = color1;
  59878. this._colorGradients.push(colorGradient);
  59879. this._colorGradients.sort(function (a, b) {
  59880. if (a.gradient < b.gradient) {
  59881. return -1;
  59882. }
  59883. else if (a.gradient > b.gradient) {
  59884. return 1;
  59885. }
  59886. return 0;
  59887. });
  59888. if (this._colorGradientsTexture) {
  59889. this._colorGradientsTexture.dispose();
  59890. this._colorGradientsTexture = null;
  59891. }
  59892. this._releaseBuffers();
  59893. return this;
  59894. };
  59895. /**
  59896. * Remove a specific color gradient
  59897. * @param gradient defines the gradient to remove
  59898. * @returns the current particle system
  59899. */
  59900. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  59901. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  59902. this._colorGradientsTexture = null;
  59903. return this;
  59904. };
  59905. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  59906. var valueGradient = new BABYLON.FactorGradient();
  59907. valueGradient.gradient = gradient;
  59908. valueGradient.factor1 = factor;
  59909. factorGradients.push(valueGradient);
  59910. factorGradients.sort(function (a, b) {
  59911. if (a.gradient < b.gradient) {
  59912. return -1;
  59913. }
  59914. else if (a.gradient > b.gradient) {
  59915. return 1;
  59916. }
  59917. return 0;
  59918. });
  59919. this._releaseBuffers();
  59920. };
  59921. /**
  59922. * Adds a new size gradient
  59923. * @param gradient defines the gradient to use (between 0 and 1)
  59924. * @param factor defines the size factor to affect to the specified gradient
  59925. * @returns the current particle system
  59926. */
  59927. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  59928. if (!this._sizeGradients) {
  59929. this._sizeGradients = [];
  59930. }
  59931. this._addFactorGradient(this._sizeGradients, gradient, factor);
  59932. if (this._sizeGradientsTexture) {
  59933. this._sizeGradientsTexture.dispose();
  59934. this._sizeGradientsTexture = null;
  59935. }
  59936. this._releaseBuffers();
  59937. return this;
  59938. };
  59939. /**
  59940. * Remove a specific size gradient
  59941. * @param gradient defines the gradient to remove
  59942. * @returns the current particle system
  59943. */
  59944. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  59945. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  59946. this._sizeGradientsTexture = null;
  59947. return this;
  59948. };
  59949. /**
  59950. * Adds a new angular speed gradient
  59951. * @param gradient defines the gradient to use (between 0 and 1)
  59952. * @param factor defines the size factor to affect to the specified gradient
  59953. * @returns the current particle system
  59954. */
  59955. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  59956. if (!this._angularSpeedGradients) {
  59957. this._angularSpeedGradients = [];
  59958. }
  59959. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  59960. if (this._angularSpeedGradientsTexture) {
  59961. this._angularSpeedGradientsTexture.dispose();
  59962. this._angularSpeedGradientsTexture = null;
  59963. }
  59964. this._releaseBuffers();
  59965. return this;
  59966. };
  59967. /**
  59968. * Remove a specific angular speed gradient
  59969. * @param gradient defines the gradient to remove
  59970. * @returns the current particle system
  59971. */
  59972. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  59973. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  59974. this._angularSpeedGradientsTexture = null;
  59975. return this;
  59976. };
  59977. /**
  59978. * Adds a new velocity gradient
  59979. * @param gradient defines the gradient to use (between 0 and 1)
  59980. * @param factor defines the size factor to affect to the specified gradient
  59981. * @returns the current particle system
  59982. */
  59983. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  59984. if (!this._velocityGradients) {
  59985. this._velocityGradients = [];
  59986. }
  59987. this._addFactorGradient(this._velocityGradients, gradient, factor);
  59988. if (this._velocityGradientsTexture) {
  59989. this._velocityGradientsTexture.dispose();
  59990. this._velocityGradientsTexture = null;
  59991. }
  59992. this._releaseBuffers();
  59993. return this;
  59994. };
  59995. /**
  59996. * Remove a specific velocity gradient
  59997. * @param gradient defines the gradient to remove
  59998. * @returns the current particle system
  59999. */
  60000. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60001. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  60002. this._velocityGradientsTexture = null;
  60003. return this;
  60004. };
  60005. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  60006. var updateVertexBuffers = {};
  60007. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  60008. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  60009. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  60010. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  60011. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  60012. var offset = 12;
  60013. if (!this._colorGradientsTexture) {
  60014. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  60015. offset += 4;
  60016. }
  60017. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  60018. offset += 3;
  60019. if (!this._isBillboardBased) {
  60020. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  60021. offset += 3;
  60022. }
  60023. if (this._angularSpeedGradientsTexture) {
  60024. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  60025. offset += 1;
  60026. }
  60027. else {
  60028. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  60029. offset += 2;
  60030. }
  60031. if (this._isAnimationSheetEnabled) {
  60032. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  60033. offset += 1;
  60034. }
  60035. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  60036. this._engine.bindArrayBuffer(null);
  60037. return vao;
  60038. };
  60039. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  60040. var renderVertexBuffers = {};
  60041. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  60042. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  60043. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  60044. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  60045. var offset = 12;
  60046. if (!this._colorGradientsTexture) {
  60047. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  60048. offset += 4;
  60049. }
  60050. offset += 3; // Direction
  60051. if (!this._isBillboardBased) {
  60052. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  60053. offset += 3;
  60054. }
  60055. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  60056. if (this._angularSpeedGradientsTexture) {
  60057. offset++;
  60058. }
  60059. else {
  60060. offset += 2;
  60061. }
  60062. if (this._isAnimationSheetEnabled) {
  60063. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  60064. offset += 1;
  60065. }
  60066. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  60067. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  60068. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  60069. this._engine.bindArrayBuffer(null);
  60070. return vao;
  60071. };
  60072. GPUParticleSystem.prototype._initialize = function (force) {
  60073. if (force === void 0) { force = false; }
  60074. if (this._buffer0 && !force) {
  60075. return;
  60076. }
  60077. var engine = this._scene.getEngine();
  60078. var data = new Array();
  60079. if (!this.isBillboardBased) {
  60080. this._attributesStrideSize += 3;
  60081. }
  60082. if (this._colorGradientsTexture) {
  60083. this._attributesStrideSize -= 4;
  60084. }
  60085. if (this._angularSpeedGradientsTexture) {
  60086. this._attributesStrideSize -= 1;
  60087. }
  60088. if (this._isAnimationSheetEnabled) {
  60089. this._attributesStrideSize += 1;
  60090. }
  60091. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  60092. // position
  60093. data.push(0.0);
  60094. data.push(0.0);
  60095. data.push(0.0);
  60096. // Age and life
  60097. data.push(0.0); // create the particle as a dead one to create a new one at start
  60098. data.push(0.0);
  60099. // Seed
  60100. data.push(Math.random());
  60101. data.push(Math.random());
  60102. data.push(Math.random());
  60103. data.push(Math.random());
  60104. // Size
  60105. data.push(0.0);
  60106. data.push(0.0);
  60107. data.push(0.0);
  60108. if (!this._colorGradientsTexture) {
  60109. // color
  60110. data.push(0.0);
  60111. data.push(0.0);
  60112. data.push(0.0);
  60113. data.push(0.0);
  60114. }
  60115. // direction
  60116. data.push(0.0);
  60117. data.push(0.0);
  60118. data.push(0.0);
  60119. if (!this.isBillboardBased) {
  60120. // initialDirection
  60121. data.push(0.0);
  60122. data.push(0.0);
  60123. data.push(0.0);
  60124. }
  60125. // angle
  60126. data.push(0.0);
  60127. if (!this._angularSpeedGradientsTexture) {
  60128. data.push(0.0);
  60129. }
  60130. if (this._isAnimationSheetEnabled) {
  60131. data.push(0.0);
  60132. }
  60133. }
  60134. // Sprite data
  60135. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  60136. -0.5, 0.5, 0, 1,
  60137. -0.5, -0.5, 0, 0,
  60138. 0.5, -0.5, 1, 0]);
  60139. // Buffers
  60140. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60141. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60142. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  60143. // Update VAO
  60144. this._updateVAO = [];
  60145. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  60146. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  60147. // Render VAO
  60148. this._renderVAO = [];
  60149. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  60150. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  60151. // Links
  60152. this._sourceBuffer = this._buffer0;
  60153. this._targetBuffer = this._buffer1;
  60154. };
  60155. /** @hidden */
  60156. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  60157. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  60158. if (this._isBillboardBased) {
  60159. defines += "\n#define BILLBOARD";
  60160. }
  60161. if (this._colorGradientsTexture) {
  60162. defines += "\n#define COLORGRADIENTS";
  60163. }
  60164. if (this._sizeGradientsTexture) {
  60165. defines += "\n#define SIZEGRADIENTS";
  60166. }
  60167. if (this._angularSpeedGradientsTexture) {
  60168. defines += "\n#define ANGULARSPEEDGRADIENTS";
  60169. }
  60170. if (this._velocityGradientsTexture) {
  60171. defines += "\n#define VELOCITYGRADIENTS";
  60172. }
  60173. if (this.isAnimationSheetEnabled) {
  60174. defines += "\n#define ANIMATESHEET";
  60175. }
  60176. if (this.noiseTexture) {
  60177. defines += "\n#define NOISE";
  60178. }
  60179. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  60180. return;
  60181. }
  60182. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  60183. if (!this._colorGradientsTexture) {
  60184. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  60185. }
  60186. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  60187. if (!this._isBillboardBased) {
  60188. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  60189. }
  60190. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  60191. if (this.isAnimationSheetEnabled) {
  60192. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  60193. }
  60194. this._updateEffectOptions.defines = defines;
  60195. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  60196. };
  60197. /** @hidden */
  60198. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  60199. var defines = "";
  60200. if (this._scene.clipPlane) {
  60201. defines = "\n#define CLIPPLANE";
  60202. }
  60203. if (this._isBillboardBased) {
  60204. defines += "\n#define BILLBOARD";
  60205. switch (this.billboardMode) {
  60206. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  60207. defines += "\n#define BILLBOARDY";
  60208. break;
  60209. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  60210. default:
  60211. break;
  60212. }
  60213. }
  60214. if (this._colorGradientsTexture) {
  60215. defines += "\n#define COLORGRADIENTS";
  60216. }
  60217. if (this.isAnimationSheetEnabled) {
  60218. defines += "\n#define ANIMATESHEET";
  60219. }
  60220. if (this._renderEffect && this._renderEffect.defines === defines) {
  60221. return;
  60222. }
  60223. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  60224. };
  60225. /**
  60226. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60227. * @param preWarm defines if we are in the pre-warmimg phase
  60228. */
  60229. GPUParticleSystem.prototype.animate = function (preWarm) {
  60230. if (preWarm === void 0) { preWarm = false; }
  60231. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60232. this._actualFrame += this._timeDelta;
  60233. if (!this._stopped) {
  60234. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  60235. this.stop();
  60236. }
  60237. }
  60238. };
  60239. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  60240. var texture = this[textureName];
  60241. if (!factorGradients || !factorGradients.length || texture) {
  60242. return;
  60243. }
  60244. var data = new Float32Array(this._rawTextureWidth);
  60245. for (var x = 0; x < this._rawTextureWidth; x++) {
  60246. var ratio = x / this._rawTextureWidth;
  60247. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  60248. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60249. });
  60250. }
  60251. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60252. };
  60253. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  60254. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  60255. };
  60256. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  60257. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  60258. };
  60259. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  60260. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  60261. };
  60262. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  60263. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  60264. return;
  60265. }
  60266. var data = new Uint8Array(this._rawTextureWidth * 4);
  60267. var tmpColor = BABYLON.Tmp.Color4[0];
  60268. for (var x = 0; x < this._rawTextureWidth; x++) {
  60269. var ratio = x / this._rawTextureWidth;
  60270. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  60271. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  60272. data[x * 4] = tmpColor.r * 255;
  60273. data[x * 4 + 1] = tmpColor.g * 255;
  60274. data[x * 4 + 2] = tmpColor.b * 255;
  60275. data[x * 4 + 3] = tmpColor.a * 255;
  60276. });
  60277. }
  60278. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60279. };
  60280. /**
  60281. * Renders the particle system in its current state
  60282. * @param preWarm defines if the system should only update the particles but not render them
  60283. * @returns the current number of particles
  60284. */
  60285. GPUParticleSystem.prototype.render = function (preWarm) {
  60286. if (preWarm === void 0) { preWarm = false; }
  60287. if (!this._started) {
  60288. return 0;
  60289. }
  60290. this._createColorGradientTexture();
  60291. this._createSizeGradientTexture();
  60292. this._createAngularSpeedGradientTexture();
  60293. this._createVelocityGradientTexture();
  60294. this._recreateUpdateEffect();
  60295. this._recreateRenderEffect();
  60296. if (!this.isReady()) {
  60297. return 0;
  60298. }
  60299. if (!preWarm) {
  60300. if (!this._preWarmDone && this.preWarmCycles) {
  60301. for (var index = 0; index < this.preWarmCycles; index++) {
  60302. this.animate(true);
  60303. this.render(true);
  60304. }
  60305. this._preWarmDone = true;
  60306. }
  60307. if (this._currentRenderId === this._scene.getRenderId()) {
  60308. return 0;
  60309. }
  60310. this._currentRenderId = this._scene.getRenderId();
  60311. }
  60312. // Get everything ready to render
  60313. this._initialize();
  60314. this._accumulatedCount += this.emitRate * this._timeDelta;
  60315. if (this._accumulatedCount > 1) {
  60316. var intPart = this._accumulatedCount | 0;
  60317. this._accumulatedCount -= intPart;
  60318. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  60319. }
  60320. if (!this._currentActiveCount) {
  60321. return 0;
  60322. }
  60323. // Enable update effect
  60324. this._engine.enableEffect(this._updateEffect);
  60325. this._engine.setState(false);
  60326. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  60327. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  60328. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  60329. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  60330. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  60331. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  60332. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  60333. if (!this._colorGradientsTexture) {
  60334. this._updateEffect.setDirectColor4("color1", this.color1);
  60335. this._updateEffect.setDirectColor4("color2", this.color2);
  60336. }
  60337. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  60338. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  60339. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  60340. this._updateEffect.setVector3("gravity", this.gravity);
  60341. if (this._sizeGradientsTexture) {
  60342. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  60343. }
  60344. if (this._angularSpeedGradientsTexture) {
  60345. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  60346. }
  60347. if (this._velocityGradientsTexture) {
  60348. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  60349. }
  60350. if (this.particleEmitterType) {
  60351. this.particleEmitterType.applyToShader(this._updateEffect);
  60352. }
  60353. if (this._isAnimationSheetEnabled) {
  60354. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  60355. }
  60356. if (this.noiseTexture) {
  60357. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  60358. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  60359. }
  60360. var emitterWM;
  60361. if (this.emitter.position) {
  60362. var emitterMesh = this.emitter;
  60363. emitterWM = emitterMesh.getWorldMatrix();
  60364. }
  60365. else {
  60366. var emitterPosition = this.emitter;
  60367. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  60368. }
  60369. this._updateEffect.setMatrix("emitterWM", emitterWM);
  60370. // Bind source VAO
  60371. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  60372. // Update
  60373. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  60374. this._engine.setRasterizerState(false);
  60375. this._engine.beginTransformFeedback(true);
  60376. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  60377. this._engine.endTransformFeedback();
  60378. this._engine.setRasterizerState(true);
  60379. this._engine.bindTransformFeedbackBuffer(null);
  60380. if (!preWarm) {
  60381. // Enable render effect
  60382. this._engine.enableEffect(this._renderEffect);
  60383. var viewMatrix = this._scene.getViewMatrix();
  60384. this._renderEffect.setMatrix("view", viewMatrix);
  60385. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  60386. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  60387. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  60388. if (this._colorGradientsTexture) {
  60389. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  60390. }
  60391. else {
  60392. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  60393. }
  60394. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60395. var baseSize = this.particleTexture.getBaseSize();
  60396. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60397. }
  60398. if (this._isBillboardBased) {
  60399. var camera = this._scene.activeCamera;
  60400. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  60401. }
  60402. if (this._scene.clipPlane) {
  60403. var clipPlane = this._scene.clipPlane;
  60404. var invView = viewMatrix.clone();
  60405. invView.invert();
  60406. this._renderEffect.setMatrix("invView", invView);
  60407. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  60408. }
  60409. // Draw order
  60410. switch (this.blendMode) {
  60411. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  60412. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60413. break;
  60414. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  60415. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60416. break;
  60417. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  60418. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60419. break;
  60420. }
  60421. if (this.forceDepthWrite) {
  60422. this._engine.setDepthWrite(true);
  60423. }
  60424. // Bind source VAO
  60425. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  60426. // Render
  60427. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  60428. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60429. }
  60430. // Switch VAOs
  60431. this._targetIndex++;
  60432. if (this._targetIndex === 2) {
  60433. this._targetIndex = 0;
  60434. }
  60435. // Switch buffers
  60436. var tmpBuffer = this._sourceBuffer;
  60437. this._sourceBuffer = this._targetBuffer;
  60438. this._targetBuffer = tmpBuffer;
  60439. return this._currentActiveCount;
  60440. };
  60441. /**
  60442. * Rebuilds the particle system
  60443. */
  60444. GPUParticleSystem.prototype.rebuild = function () {
  60445. this._initialize(true);
  60446. };
  60447. GPUParticleSystem.prototype._releaseBuffers = function () {
  60448. if (this._buffer0) {
  60449. this._buffer0.dispose();
  60450. this._buffer0 = null;
  60451. }
  60452. if (this._buffer1) {
  60453. this._buffer1.dispose();
  60454. this._buffer1 = null;
  60455. }
  60456. if (this._spriteBuffer) {
  60457. this._spriteBuffer.dispose();
  60458. this._spriteBuffer = null;
  60459. }
  60460. };
  60461. GPUParticleSystem.prototype._releaseVAOs = function () {
  60462. if (!this._updateVAO) {
  60463. return;
  60464. }
  60465. for (var index = 0; index < this._updateVAO.length; index++) {
  60466. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  60467. }
  60468. this._updateVAO = [];
  60469. for (var index = 0; index < this._renderVAO.length; index++) {
  60470. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  60471. }
  60472. this._renderVAO = [];
  60473. };
  60474. /**
  60475. * Disposes the particle system and free the associated resources
  60476. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60477. */
  60478. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  60479. if (disposeTexture === void 0) { disposeTexture = true; }
  60480. var index = this._scene.particleSystems.indexOf(this);
  60481. if (index > -1) {
  60482. this._scene.particleSystems.splice(index, 1);
  60483. }
  60484. this._releaseBuffers();
  60485. this._releaseVAOs();
  60486. if (this._colorGradientsTexture) {
  60487. this._colorGradientsTexture.dispose();
  60488. this._colorGradientsTexture = null;
  60489. }
  60490. if (this._sizeGradientsTexture) {
  60491. this._sizeGradientsTexture.dispose();
  60492. this._sizeGradientsTexture = null;
  60493. }
  60494. if (this._angularSpeedGradientsTexture) {
  60495. this._angularSpeedGradientsTexture.dispose();
  60496. this._angularSpeedGradientsTexture = null;
  60497. }
  60498. if (this._velocityGradientsTexture) {
  60499. this._velocityGradientsTexture.dispose();
  60500. this._velocityGradientsTexture = null;
  60501. }
  60502. if (this._randomTexture) {
  60503. this._randomTexture.dispose();
  60504. this._randomTexture = null;
  60505. }
  60506. if (this._randomTexture2) {
  60507. this._randomTexture2.dispose();
  60508. this._randomTexture2 = null;
  60509. }
  60510. if (disposeTexture && this.particleTexture) {
  60511. this.particleTexture.dispose();
  60512. this.particleTexture = null;
  60513. }
  60514. if (disposeTexture && this.noiseTexture) {
  60515. this.noiseTexture.dispose();
  60516. this.noiseTexture = null;
  60517. }
  60518. // Callback
  60519. this.onDisposeObservable.notifyObservers(this);
  60520. this.onDisposeObservable.clear();
  60521. };
  60522. /**
  60523. * Clones the particle system.
  60524. * @param name The name of the cloned object
  60525. * @param newEmitter The new emitter to use
  60526. * @returns the cloned particle system
  60527. */
  60528. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  60529. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  60530. BABYLON.Tools.DeepCopy(this, result);
  60531. if (newEmitter === undefined) {
  60532. newEmitter = this.emitter;
  60533. }
  60534. result.emitter = newEmitter;
  60535. if (this.particleTexture) {
  60536. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60537. }
  60538. return result;
  60539. };
  60540. /**
  60541. * Serializes the particle system to a JSON object.
  60542. * @returns the JSON object
  60543. */
  60544. GPUParticleSystem.prototype.serialize = function () {
  60545. var serializationObject = {};
  60546. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  60547. serializationObject.activeParticleCount = this.activeParticleCount;
  60548. return serializationObject;
  60549. };
  60550. /**
  60551. * Parses a JSON object to create a GPU particle system.
  60552. * @param parsedParticleSystem The JSON object to parse
  60553. * @param scene The scene to create the particle system in
  60554. * @param rootUrl The root url to use to load external dependencies like texture
  60555. * @returns the parsed GPU particle system
  60556. */
  60557. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  60558. var name = parsedParticleSystem.name;
  60559. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  60560. if (parsedParticleSystem.activeParticleCount) {
  60561. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  60562. }
  60563. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60564. return particleSystem;
  60565. };
  60566. return GPUParticleSystem;
  60567. }());
  60568. BABYLON.GPUParticleSystem = GPUParticleSystem;
  60569. })(BABYLON || (BABYLON = {}));
  60570. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  60571. var BABYLON;
  60572. (function (BABYLON) {
  60573. /**
  60574. * Represents one particle of a solid particle system.
  60575. */
  60576. var SolidParticle = /** @class */ (function () {
  60577. /**
  60578. * Creates a Solid Particle object.
  60579. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  60580. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  60581. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  60582. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  60583. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  60584. * @param shapeId (integer) is the model shape identifier in the SPS.
  60585. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  60586. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  60587. */
  60588. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  60589. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  60590. /**
  60591. * particle global index
  60592. */
  60593. this.idx = 0;
  60594. /**
  60595. * The color of the particle
  60596. */
  60597. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60598. /**
  60599. * The world space position of the particle.
  60600. */
  60601. this.position = BABYLON.Vector3.Zero();
  60602. /**
  60603. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  60604. */
  60605. this.rotation = BABYLON.Vector3.Zero();
  60606. /**
  60607. * The scaling of the particle.
  60608. */
  60609. this.scaling = BABYLON.Vector3.One();
  60610. /**
  60611. * The uvs of the particle.
  60612. */
  60613. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  60614. /**
  60615. * The current speed of the particle.
  60616. */
  60617. this.velocity = BABYLON.Vector3.Zero();
  60618. /**
  60619. * The pivot point in the particle local space.
  60620. */
  60621. this.pivot = BABYLON.Vector3.Zero();
  60622. /**
  60623. * Must the particle be translated from its pivot point in its local space ?
  60624. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  60625. * Default : false
  60626. */
  60627. this.translateFromPivot = false;
  60628. /**
  60629. * Is the particle active or not ?
  60630. */
  60631. this.alive = true;
  60632. /**
  60633. * Is the particle visible or not ?
  60634. */
  60635. this.isVisible = true;
  60636. /**
  60637. * Index of this particle in the global "positions" array (Internal use)
  60638. */
  60639. this._pos = 0;
  60640. /**
  60641. * Index of this particle in the global "indices" array (Internal use)
  60642. */
  60643. this._ind = 0;
  60644. /**
  60645. * ModelShape id of this particle
  60646. */
  60647. this.shapeId = 0;
  60648. /**
  60649. * Index of the particle in its shape id (Internal use)
  60650. */
  60651. this.idxInShape = 0;
  60652. /**
  60653. * Still set as invisible in order to skip useless computations (Internal use)
  60654. */
  60655. this._stillInvisible = false;
  60656. /**
  60657. * Last computed particle rotation matrix
  60658. */
  60659. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  60660. /**
  60661. * Parent particle Id, if any.
  60662. * Default null.
  60663. */
  60664. this.parentId = null;
  60665. /**
  60666. * Internal global position in the SPS.
  60667. */
  60668. this._globalPosition = BABYLON.Vector3.Zero();
  60669. this.idx = particleIndex;
  60670. this._pos = positionIndex;
  60671. this._ind = indiceIndex;
  60672. this._model = model;
  60673. this.shapeId = shapeId;
  60674. this.idxInShape = idxInShape;
  60675. this._sps = sps;
  60676. if (modelBoundingInfo) {
  60677. this._modelBoundingInfo = modelBoundingInfo;
  60678. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  60679. }
  60680. }
  60681. Object.defineProperty(SolidParticle.prototype, "scale", {
  60682. /**
  60683. * Legacy support, changed scale to scaling
  60684. */
  60685. get: function () {
  60686. return this.scaling;
  60687. },
  60688. /**
  60689. * Legacy support, changed scale to scaling
  60690. */
  60691. set: function (scale) {
  60692. this.scaling = scale;
  60693. },
  60694. enumerable: true,
  60695. configurable: true
  60696. });
  60697. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  60698. /**
  60699. * Legacy support, changed quaternion to rotationQuaternion
  60700. */
  60701. get: function () {
  60702. return this.rotationQuaternion;
  60703. },
  60704. /**
  60705. * Legacy support, changed quaternion to rotationQuaternion
  60706. */
  60707. set: function (q) {
  60708. this.rotationQuaternion = q;
  60709. },
  60710. enumerable: true,
  60711. configurable: true
  60712. });
  60713. /**
  60714. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  60715. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  60716. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  60717. * @returns true if it intersects
  60718. */
  60719. SolidParticle.prototype.intersectsMesh = function (target) {
  60720. if (!this._boundingInfo || !target._boundingInfo) {
  60721. return false;
  60722. }
  60723. if (this._sps._bSphereOnly) {
  60724. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  60725. }
  60726. return this._boundingInfo.intersects(target._boundingInfo, false);
  60727. };
  60728. return SolidParticle;
  60729. }());
  60730. BABYLON.SolidParticle = SolidParticle;
  60731. /**
  60732. * Represents the shape of the model used by one particle of a solid particle system.
  60733. * SPS internal tool, don't use it manually.
  60734. */
  60735. var ModelShape = /** @class */ (function () {
  60736. /**
  60737. * 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.
  60738. * SPS internal tool, don't use it manually.
  60739. * @hidden
  60740. */
  60741. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  60742. /**
  60743. * length of the shape in the model indices array (internal use)
  60744. */
  60745. this._indicesLength = 0;
  60746. this.shapeID = id;
  60747. this._shape = shape;
  60748. this._indicesLength = indicesLength;
  60749. this._shapeUV = shapeUV;
  60750. this._positionFunction = posFunction;
  60751. this._vertexFunction = vtxFunction;
  60752. }
  60753. return ModelShape;
  60754. }());
  60755. BABYLON.ModelShape = ModelShape;
  60756. /**
  60757. * Represents a Depth Sorted Particle in the solid particle system.
  60758. */
  60759. var DepthSortedParticle = /** @class */ (function () {
  60760. function DepthSortedParticle() {
  60761. /**
  60762. * Index of the particle in the "indices" array
  60763. */
  60764. this.ind = 0;
  60765. /**
  60766. * Length of the particle shape in the "indices" array
  60767. */
  60768. this.indicesLength = 0;
  60769. /**
  60770. * Squared distance from the particle to the camera
  60771. */
  60772. this.sqDistance = 0.0;
  60773. }
  60774. return DepthSortedParticle;
  60775. }());
  60776. BABYLON.DepthSortedParticle = DepthSortedParticle;
  60777. })(BABYLON || (BABYLON = {}));
  60778. //# sourceMappingURL=babylon.solidParticle.js.map
  60779. var BABYLON;
  60780. (function (BABYLON) {
  60781. /**
  60782. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  60783. *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.
  60784. * The SPS is also a particle system. It provides some methods to manage the particles.
  60785. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  60786. *
  60787. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  60788. */
  60789. var SolidParticleSystem = /** @class */ (function () {
  60790. /**
  60791. * Creates a SPS (Solid Particle System) object.
  60792. * @param name (String) is the SPS name, this will be the underlying mesh name.
  60793. * @param scene (Scene) is the scene in which the SPS is added.
  60794. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  60795. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  60796. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  60797. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  60798. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  60799. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  60800. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  60801. */
  60802. function SolidParticleSystem(name, scene, options) {
  60803. /**
  60804. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  60805. * Example : var p = SPS.particles[i];
  60806. */
  60807. this.particles = new Array();
  60808. /**
  60809. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  60810. */
  60811. this.nbParticles = 0;
  60812. /**
  60813. * If the particles must ever face the camera (default false). Useful for planar particles.
  60814. */
  60815. this.billboard = false;
  60816. /**
  60817. * Recompute normals when adding a shape
  60818. */
  60819. this.recomputeNormals = true;
  60820. /**
  60821. * This a counter ofr your own usage. It's not set by any SPS functions.
  60822. */
  60823. this.counter = 0;
  60824. /**
  60825. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  60826. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  60827. */
  60828. this.vars = {};
  60829. /**
  60830. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  60831. */
  60832. this._bSphereOnly = false;
  60833. /**
  60834. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  60835. */
  60836. this._bSphereRadiusFactor = 1.0;
  60837. this._positions = new Array();
  60838. this._indices = new Array();
  60839. this._normals = new Array();
  60840. this._colors = new Array();
  60841. this._uvs = new Array();
  60842. this._index = 0; // indices index
  60843. this._updatable = true;
  60844. this._pickable = false;
  60845. this._isVisibilityBoxLocked = false;
  60846. this._alwaysVisible = false;
  60847. this._depthSort = false;
  60848. this._shapeCounter = 0;
  60849. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  60850. this._color = new BABYLON.Color4(0, 0, 0, 0);
  60851. this._computeParticleColor = true;
  60852. this._computeParticleTexture = true;
  60853. this._computeParticleRotation = true;
  60854. this._computeParticleVertex = false;
  60855. this._computeBoundingBox = false;
  60856. this._depthSortParticles = true;
  60857. this._cam_axisZ = BABYLON.Vector3.Zero();
  60858. this._cam_axisY = BABYLON.Vector3.Zero();
  60859. this._cam_axisX = BABYLON.Vector3.Zero();
  60860. this._axisZ = BABYLON.Axis.Z;
  60861. this._camDir = BABYLON.Vector3.Zero();
  60862. this._camInvertedPosition = BABYLON.Vector3.Zero();
  60863. this._rotMatrix = new BABYLON.Matrix();
  60864. this._invertMatrix = new BABYLON.Matrix();
  60865. this._rotated = BABYLON.Vector3.Zero();
  60866. this._quaternion = new BABYLON.Quaternion();
  60867. this._vertex = BABYLON.Vector3.Zero();
  60868. this._normal = BABYLON.Vector3.Zero();
  60869. this._yaw = 0.0;
  60870. this._pitch = 0.0;
  60871. this._roll = 0.0;
  60872. this._halfroll = 0.0;
  60873. this._halfpitch = 0.0;
  60874. this._halfyaw = 0.0;
  60875. this._sinRoll = 0.0;
  60876. this._cosRoll = 0.0;
  60877. this._sinPitch = 0.0;
  60878. this._cosPitch = 0.0;
  60879. this._sinYaw = 0.0;
  60880. this._cosYaw = 0.0;
  60881. this._mustUnrotateFixedNormals = false;
  60882. this._minimum = BABYLON.Vector3.Zero();
  60883. this._maximum = BABYLON.Vector3.Zero();
  60884. this._minBbox = BABYLON.Vector3.Zero();
  60885. this._maxBbox = BABYLON.Vector3.Zero();
  60886. this._particlesIntersect = false;
  60887. this._depthSortFunction = function (p1, p2) {
  60888. return (p2.sqDistance - p1.sqDistance);
  60889. };
  60890. this._needs32Bits = false;
  60891. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  60892. this._scaledPivot = BABYLON.Vector3.Zero();
  60893. this._particleHasParent = false;
  60894. this.name = name;
  60895. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60896. this._camera = scene.activeCamera;
  60897. this._pickable = options ? options.isPickable : false;
  60898. this._depthSort = options ? options.enableDepthSort : false;
  60899. this._particlesIntersect = options ? options.particleIntersection : false;
  60900. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  60901. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  60902. if (options && options.updatable !== undefined) {
  60903. this._updatable = options.updatable;
  60904. }
  60905. else {
  60906. this._updatable = true;
  60907. }
  60908. if (this._pickable) {
  60909. this.pickedParticles = [];
  60910. }
  60911. if (this._depthSort) {
  60912. this.depthSortedParticles = [];
  60913. }
  60914. }
  60915. /**
  60916. * Builds the SPS underlying mesh. Returns a standard Mesh.
  60917. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  60918. * @returns the created mesh
  60919. */
  60920. SolidParticleSystem.prototype.buildMesh = function () {
  60921. if (this.nbParticles === 0) {
  60922. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  60923. this.addShape(triangle, 1);
  60924. triangle.dispose();
  60925. }
  60926. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  60927. this._positions32 = new Float32Array(this._positions);
  60928. this._uvs32 = new Float32Array(this._uvs);
  60929. this._colors32 = new Float32Array(this._colors);
  60930. if (this.recomputeNormals) {
  60931. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  60932. }
  60933. this._normals32 = new Float32Array(this._normals);
  60934. this._fixedNormal32 = new Float32Array(this._normals);
  60935. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  60936. this._unrotateFixedNormals();
  60937. }
  60938. var vertexData = new BABYLON.VertexData();
  60939. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  60940. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  60941. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  60942. if (this._uvs32.length > 0) {
  60943. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  60944. }
  60945. if (this._colors32.length > 0) {
  60946. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  60947. }
  60948. var mesh = new BABYLON.Mesh(this.name, this._scene);
  60949. vertexData.applyToMesh(mesh, this._updatable);
  60950. this.mesh = mesh;
  60951. this.mesh.isPickable = this._pickable;
  60952. // free memory
  60953. if (!this._depthSort) {
  60954. this._indices = null;
  60955. }
  60956. this._positions = null;
  60957. this._normals = null;
  60958. this._uvs = null;
  60959. this._colors = null;
  60960. if (!this._updatable) {
  60961. this.particles.length = 0;
  60962. }
  60963. return mesh;
  60964. };
  60965. /**
  60966. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  60967. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  60968. * Thus the particles generated from `digest()` have their property `position` set yet.
  60969. * @param mesh ( Mesh ) is the mesh to be digested
  60970. * @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
  60971. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  60972. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  60973. * @returns the current SPS
  60974. */
  60975. SolidParticleSystem.prototype.digest = function (mesh, options) {
  60976. var size = (options && options.facetNb) || 1;
  60977. var number = (options && options.number) || 0;
  60978. var delta = (options && options.delta) || 0;
  60979. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60980. var meshInd = mesh.getIndices();
  60981. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60982. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60983. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60984. var f = 0; // facet counter
  60985. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  60986. // compute size from number
  60987. if (number) {
  60988. number = (number > totalFacets) ? totalFacets : number;
  60989. size = Math.round(totalFacets / number);
  60990. delta = 0;
  60991. }
  60992. else {
  60993. size = (size > totalFacets) ? totalFacets : size;
  60994. }
  60995. var facetPos = []; // submesh positions
  60996. var facetInd = []; // submesh indices
  60997. var facetUV = []; // submesh UV
  60998. var facetCol = []; // submesh colors
  60999. var barycenter = BABYLON.Vector3.Zero();
  61000. var sizeO = size;
  61001. while (f < totalFacets) {
  61002. size = sizeO + Math.floor((1 + delta) * Math.random());
  61003. if (f > totalFacets - size) {
  61004. size = totalFacets - f;
  61005. }
  61006. // reset temp arrays
  61007. facetPos.length = 0;
  61008. facetInd.length = 0;
  61009. facetUV.length = 0;
  61010. facetCol.length = 0;
  61011. // iterate over "size" facets
  61012. var fi = 0;
  61013. for (var j = f * 3; j < (f + size) * 3; j++) {
  61014. facetInd.push(fi);
  61015. var i = meshInd[j];
  61016. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  61017. if (meshUV) {
  61018. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  61019. }
  61020. if (meshCol) {
  61021. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  61022. }
  61023. fi++;
  61024. }
  61025. // create a model shape for each single particle
  61026. var idx = this.nbParticles;
  61027. var shape = this._posToShape(facetPos);
  61028. var shapeUV = this._uvsToShapeUV(facetUV);
  61029. // compute the barycenter of the shape
  61030. var v;
  61031. for (v = 0; v < shape.length; v++) {
  61032. barycenter.addInPlace(shape[v]);
  61033. }
  61034. barycenter.scaleInPlace(1 / shape.length);
  61035. // shift the shape from its barycenter to the origin
  61036. for (v = 0; v < shape.length; v++) {
  61037. shape[v].subtractInPlace(barycenter);
  61038. }
  61039. var bInfo;
  61040. if (this._particlesIntersect) {
  61041. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  61042. }
  61043. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  61044. // add the particle in the SPS
  61045. var currentPos = this._positions.length;
  61046. var currentInd = this._indices.length;
  61047. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  61048. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  61049. // initialize the particle position
  61050. this.particles[this.nbParticles].position.addInPlace(barycenter);
  61051. this._index += shape.length;
  61052. idx++;
  61053. this.nbParticles++;
  61054. this._shapeCounter++;
  61055. f += size;
  61056. }
  61057. return this;
  61058. };
  61059. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  61060. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  61061. var index = 0;
  61062. var idx = 0;
  61063. for (var p = 0; p < this.particles.length; p++) {
  61064. this._particle = this.particles[p];
  61065. this._shape = this._particle._model._shape;
  61066. if (this._particle.rotationQuaternion) {
  61067. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61068. }
  61069. else {
  61070. this._yaw = this._particle.rotation.y;
  61071. this._pitch = this._particle.rotation.x;
  61072. this._roll = this._particle.rotation.z;
  61073. this._quaternionRotationYPR();
  61074. }
  61075. this._quaternionToRotationMatrix();
  61076. this._rotMatrix.invertToRef(this._invertMatrix);
  61077. for (var pt = 0; pt < this._shape.length; pt++) {
  61078. idx = index + pt * 3;
  61079. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  61080. this._fixedNormal32[idx] = this._normal.x;
  61081. this._fixedNormal32[idx + 1] = this._normal.y;
  61082. this._fixedNormal32[idx + 2] = this._normal.z;
  61083. }
  61084. index = idx + 3;
  61085. }
  61086. };
  61087. //reset copy
  61088. SolidParticleSystem.prototype._resetCopy = function () {
  61089. this._copy.position.x = 0;
  61090. this._copy.position.y = 0;
  61091. this._copy.position.z = 0;
  61092. this._copy.rotation.x = 0;
  61093. this._copy.rotation.y = 0;
  61094. this._copy.rotation.z = 0;
  61095. this._copy.rotationQuaternion = null;
  61096. this._copy.scaling.x = 1.0;
  61097. this._copy.scaling.y = 1.0;
  61098. this._copy.scaling.z = 1.0;
  61099. this._copy.uvs.x = 0;
  61100. this._copy.uvs.y = 0;
  61101. this._copy.uvs.z = 1.0;
  61102. this._copy.uvs.w = 1.0;
  61103. this._copy.color = null;
  61104. this._copy.translateFromPivot = false;
  61105. };
  61106. // _meshBuilder : inserts the shape model in the global SPS mesh
  61107. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  61108. var i;
  61109. var u = 0;
  61110. var c = 0;
  61111. var n = 0;
  61112. this._resetCopy();
  61113. if (options && options.positionFunction) { // call to custom positionFunction
  61114. options.positionFunction(this._copy, idx, idxInShape);
  61115. this._mustUnrotateFixedNormals = true;
  61116. }
  61117. if (this._copy.rotationQuaternion) {
  61118. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61119. }
  61120. else {
  61121. this._yaw = this._copy.rotation.y;
  61122. this._pitch = this._copy.rotation.x;
  61123. this._roll = this._copy.rotation.z;
  61124. this._quaternionRotationYPR();
  61125. }
  61126. this._quaternionToRotationMatrix();
  61127. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  61128. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  61129. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  61130. if (this._copy.translateFromPivot) {
  61131. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61132. }
  61133. else {
  61134. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61135. }
  61136. for (i = 0; i < shape.length; i++) {
  61137. this._vertex.x = shape[i].x;
  61138. this._vertex.y = shape[i].y;
  61139. this._vertex.z = shape[i].z;
  61140. if (options && options.vertexFunction) {
  61141. options.vertexFunction(this._copy, this._vertex, i);
  61142. }
  61143. this._vertex.x *= this._copy.scaling.x;
  61144. this._vertex.y *= this._copy.scaling.y;
  61145. this._vertex.z *= this._copy.scaling.z;
  61146. this._vertex.x -= this._scaledPivot.x;
  61147. this._vertex.y -= this._scaledPivot.y;
  61148. this._vertex.z -= this._scaledPivot.z;
  61149. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61150. this._rotated.addInPlace(this._pivotBackTranslation);
  61151. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  61152. if (meshUV) {
  61153. 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);
  61154. u += 2;
  61155. }
  61156. if (this._copy.color) {
  61157. this._color = this._copy.color;
  61158. }
  61159. else if (meshCol && meshCol[c] !== undefined) {
  61160. this._color.r = meshCol[c];
  61161. this._color.g = meshCol[c + 1];
  61162. this._color.b = meshCol[c + 2];
  61163. this._color.a = meshCol[c + 3];
  61164. }
  61165. else {
  61166. this._color.r = 1.0;
  61167. this._color.g = 1.0;
  61168. this._color.b = 1.0;
  61169. this._color.a = 1.0;
  61170. }
  61171. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  61172. c += 4;
  61173. if (!this.recomputeNormals && meshNor) {
  61174. this._normal.x = meshNor[n];
  61175. this._normal.y = meshNor[n + 1];
  61176. this._normal.z = meshNor[n + 2];
  61177. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  61178. normals.push(this._normal.x, this._normal.y, this._normal.z);
  61179. n += 3;
  61180. }
  61181. }
  61182. for (i = 0; i < meshInd.length; i++) {
  61183. var current_ind = p + meshInd[i];
  61184. indices.push(current_ind);
  61185. if (current_ind > 65535) {
  61186. this._needs32Bits = true;
  61187. }
  61188. }
  61189. if (this._pickable) {
  61190. var nbfaces = meshInd.length / 3;
  61191. for (i = 0; i < nbfaces; i++) {
  61192. this.pickedParticles.push({ idx: idx, faceId: i });
  61193. }
  61194. }
  61195. if (this._depthSort) {
  61196. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  61197. }
  61198. return this._copy;
  61199. };
  61200. // returns a shape array from positions array
  61201. SolidParticleSystem.prototype._posToShape = function (positions) {
  61202. var shape = [];
  61203. for (var i = 0; i < positions.length; i += 3) {
  61204. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  61205. }
  61206. return shape;
  61207. };
  61208. // returns a shapeUV array from a Vector4 uvs
  61209. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  61210. var shapeUV = [];
  61211. if (uvs) {
  61212. for (var i = 0; i < uvs.length; i++)
  61213. shapeUV.push(uvs[i]);
  61214. }
  61215. return shapeUV;
  61216. };
  61217. // adds a new particle object in the particles array
  61218. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  61219. if (bInfo === void 0) { bInfo = null; }
  61220. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  61221. this.particles.push(sp);
  61222. return sp;
  61223. };
  61224. /**
  61225. * Adds some particles to the SPS from the model shape. Returns the shape id.
  61226. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  61227. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  61228. * @param nb (positive integer) the number of particles to be created from this model
  61229. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  61230. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  61231. * @returns the number of shapes in the system
  61232. */
  61233. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  61234. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61235. var meshInd = mesh.getIndices();
  61236. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61237. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61238. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61239. var bbInfo;
  61240. if (this._particlesIntersect) {
  61241. bbInfo = mesh.getBoundingInfo();
  61242. }
  61243. var shape = this._posToShape(meshPos);
  61244. var shapeUV = this._uvsToShapeUV(meshUV);
  61245. var posfunc = options ? options.positionFunction : null;
  61246. var vtxfunc = options ? options.vertexFunction : null;
  61247. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  61248. // particles
  61249. var sp;
  61250. var currentCopy;
  61251. var idx = this.nbParticles;
  61252. for (var i = 0; i < nb; i++) {
  61253. var currentPos = this._positions.length;
  61254. var currentInd = this._indices.length;
  61255. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  61256. if (this._updatable) {
  61257. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  61258. sp.position.copyFrom(currentCopy.position);
  61259. sp.rotation.copyFrom(currentCopy.rotation);
  61260. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  61261. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  61262. }
  61263. if (currentCopy.color && sp.color) {
  61264. sp.color.copyFrom(currentCopy.color);
  61265. }
  61266. sp.scaling.copyFrom(currentCopy.scaling);
  61267. sp.uvs.copyFrom(currentCopy.uvs);
  61268. }
  61269. this._index += shape.length;
  61270. idx++;
  61271. }
  61272. this.nbParticles += nb;
  61273. this._shapeCounter++;
  61274. return this._shapeCounter - 1;
  61275. };
  61276. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  61277. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  61278. this._resetCopy();
  61279. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  61280. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  61281. }
  61282. if (this._copy.rotationQuaternion) {
  61283. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61284. }
  61285. else {
  61286. this._yaw = this._copy.rotation.y;
  61287. this._pitch = this._copy.rotation.x;
  61288. this._roll = this._copy.rotation.z;
  61289. this._quaternionRotationYPR();
  61290. }
  61291. this._quaternionToRotationMatrix();
  61292. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61293. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61294. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61295. if (this._copy.translateFromPivot) {
  61296. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61297. }
  61298. else {
  61299. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61300. }
  61301. this._shape = particle._model._shape;
  61302. for (var pt = 0; pt < this._shape.length; pt++) {
  61303. this._vertex.x = this._shape[pt].x;
  61304. this._vertex.y = this._shape[pt].y;
  61305. this._vertex.z = this._shape[pt].z;
  61306. if (particle._model._vertexFunction) {
  61307. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  61308. }
  61309. this._vertex.x *= this._copy.scaling.x;
  61310. this._vertex.y *= this._copy.scaling.y;
  61311. this._vertex.z *= this._copy.scaling.z;
  61312. this._vertex.x -= this._scaledPivot.x;
  61313. this._vertex.y -= this._scaledPivot.y;
  61314. this._vertex.z -= this._scaledPivot.z;
  61315. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61316. this._rotated.addInPlace(this._pivotBackTranslation);
  61317. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  61318. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  61319. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  61320. }
  61321. particle.position.x = 0.0;
  61322. particle.position.y = 0.0;
  61323. particle.position.z = 0.0;
  61324. particle.rotation.x = 0.0;
  61325. particle.rotation.y = 0.0;
  61326. particle.rotation.z = 0.0;
  61327. particle.rotationQuaternion = null;
  61328. particle.scaling.x = 1.0;
  61329. particle.scaling.y = 1.0;
  61330. particle.scaling.z = 1.0;
  61331. particle.uvs.x = 0.0;
  61332. particle.uvs.y = 0.0;
  61333. particle.uvs.z = 1.0;
  61334. particle.uvs.w = 1.0;
  61335. particle.pivot.x = 0.0;
  61336. particle.pivot.y = 0.0;
  61337. particle.pivot.z = 0.0;
  61338. particle.translateFromPivot = false;
  61339. particle.parentId = null;
  61340. };
  61341. /**
  61342. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  61343. * @returns the SPS.
  61344. */
  61345. SolidParticleSystem.prototype.rebuildMesh = function () {
  61346. for (var p = 0; p < this.particles.length; p++) {
  61347. this._rebuildParticle(this.particles[p]);
  61348. }
  61349. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61350. return this;
  61351. };
  61352. /**
  61353. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  61354. * This method calls `updateParticle()` for each particle of the SPS.
  61355. * For an animated SPS, it is usually called within the render loop.
  61356. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  61357. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  61358. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  61359. * @returns the SPS.
  61360. */
  61361. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  61362. if (start === void 0) { start = 0; }
  61363. if (end === void 0) { end = this.nbParticles - 1; }
  61364. if (update === void 0) { update = true; }
  61365. if (!this._updatable) {
  61366. return this;
  61367. }
  61368. // custom beforeUpdate
  61369. this.beforeUpdateParticles(start, end, update);
  61370. this._cam_axisX.x = 1.0;
  61371. this._cam_axisX.y = 0.0;
  61372. this._cam_axisX.z = 0.0;
  61373. this._cam_axisY.x = 0.0;
  61374. this._cam_axisY.y = 1.0;
  61375. this._cam_axisY.z = 0.0;
  61376. this._cam_axisZ.x = 0.0;
  61377. this._cam_axisZ.y = 0.0;
  61378. this._cam_axisZ.z = 1.0;
  61379. // cases when the World Matrix is to be computed first
  61380. if (this.billboard || this._depthSort) {
  61381. this.mesh.computeWorldMatrix(true);
  61382. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  61383. }
  61384. // if the particles will always face the camera
  61385. if (this.billboard) {
  61386. // compute the camera position and un-rotate it by the current mesh rotation
  61387. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  61388. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  61389. this._cam_axisZ.normalize();
  61390. // same for camera up vector extracted from the cam view matrix
  61391. var view = this._camera.getViewMatrix(true);
  61392. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  61393. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  61394. this._cam_axisY.normalize();
  61395. this._cam_axisX.normalize();
  61396. }
  61397. // if depthSort, compute the camera global position in the mesh local system
  61398. if (this._depthSort) {
  61399. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  61400. }
  61401. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  61402. var idx = 0; // current position index in the global array positions32
  61403. var index = 0; // position start index in the global array positions32 of the current particle
  61404. var colidx = 0; // current color index in the global array colors32
  61405. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  61406. var uvidx = 0; // current uv index in the global array uvs32
  61407. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  61408. var pt = 0; // current index in the particle model shape
  61409. if (this.mesh.isFacetDataEnabled) {
  61410. this._computeBoundingBox = true;
  61411. }
  61412. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  61413. if (this._computeBoundingBox) {
  61414. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  61415. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  61416. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  61417. }
  61418. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  61419. if (this.mesh._boundingInfo) {
  61420. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  61421. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  61422. }
  61423. }
  61424. }
  61425. // particle loop
  61426. index = this.particles[start]._pos;
  61427. var vpos = (index / 3) | 0;
  61428. colorIndex = vpos * 4;
  61429. uvIndex = vpos * 2;
  61430. for (var p = start; p <= end; p++) {
  61431. this._particle = this.particles[p];
  61432. this._shape = this._particle._model._shape;
  61433. this._shapeUV = this._particle._model._shapeUV;
  61434. // call to custom user function to update the particle properties
  61435. this.updateParticle(this._particle);
  61436. // camera-particle distance for depth sorting
  61437. if (this._depthSort && this._depthSortParticles) {
  61438. var dsp = this.depthSortedParticles[p];
  61439. dsp.ind = this._particle._ind;
  61440. dsp.indicesLength = this._particle._model._indicesLength;
  61441. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  61442. }
  61443. // skip the computations for inactive or already invisible particles
  61444. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  61445. // increment indexes for the next particle
  61446. pt = this._shape.length;
  61447. index += pt * 3;
  61448. colorIndex += pt * 4;
  61449. uvIndex += pt * 2;
  61450. continue;
  61451. }
  61452. if (this._particle.isVisible) {
  61453. this._particle._stillInvisible = false; // un-mark permanent invisibility
  61454. this._particleHasParent = (this._particle.parentId !== null);
  61455. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61456. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61457. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61458. // particle rotation matrix
  61459. if (this.billboard) {
  61460. this._particle.rotation.x = 0.0;
  61461. this._particle.rotation.y = 0.0;
  61462. }
  61463. if (this._computeParticleRotation || this.billboard) {
  61464. if (this._particle.rotationQuaternion) {
  61465. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61466. }
  61467. else {
  61468. this._yaw = this._particle.rotation.y;
  61469. this._pitch = this._particle.rotation.x;
  61470. this._roll = this._particle.rotation.z;
  61471. this._quaternionRotationYPR();
  61472. }
  61473. this._quaternionToRotationMatrix();
  61474. }
  61475. if (this._particleHasParent) {
  61476. this._parent = this.particles[this._particle.parentId];
  61477. 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];
  61478. 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];
  61479. 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];
  61480. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  61481. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  61482. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  61483. if (this._computeParticleRotation || this.billboard) {
  61484. 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];
  61485. 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];
  61486. 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];
  61487. 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];
  61488. 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];
  61489. 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];
  61490. 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];
  61491. 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];
  61492. 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];
  61493. }
  61494. }
  61495. else {
  61496. this._particle._globalPosition.x = this._particle.position.x;
  61497. this._particle._globalPosition.y = this._particle.position.y;
  61498. this._particle._globalPosition.z = this._particle.position.z;
  61499. if (this._computeParticleRotation || this.billboard) {
  61500. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  61501. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  61502. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  61503. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  61504. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  61505. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  61506. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  61507. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  61508. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  61509. }
  61510. }
  61511. if (this._particle.translateFromPivot) {
  61512. this._pivotBackTranslation.x = 0.0;
  61513. this._pivotBackTranslation.y = 0.0;
  61514. this._pivotBackTranslation.z = 0.0;
  61515. }
  61516. else {
  61517. this._pivotBackTranslation.x = this._scaledPivot.x;
  61518. this._pivotBackTranslation.y = this._scaledPivot.y;
  61519. this._pivotBackTranslation.z = this._scaledPivot.z;
  61520. }
  61521. // particle vertex loop
  61522. for (pt = 0; pt < this._shape.length; pt++) {
  61523. idx = index + pt * 3;
  61524. colidx = colorIndex + pt * 4;
  61525. uvidx = uvIndex + pt * 2;
  61526. this._vertex.x = this._shape[pt].x;
  61527. this._vertex.y = this._shape[pt].y;
  61528. this._vertex.z = this._shape[pt].z;
  61529. if (this._computeParticleVertex) {
  61530. this.updateParticleVertex(this._particle, this._vertex, pt);
  61531. }
  61532. // positions
  61533. this._vertex.x *= this._particle.scaling.x;
  61534. this._vertex.y *= this._particle.scaling.y;
  61535. this._vertex.z *= this._particle.scaling.z;
  61536. this._vertex.x -= this._scaledPivot.x;
  61537. this._vertex.y -= this._scaledPivot.y;
  61538. this._vertex.z -= this._scaledPivot.z;
  61539. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61540. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61541. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61542. this._rotated.x += this._pivotBackTranslation.x;
  61543. this._rotated.y += this._pivotBackTranslation.y;
  61544. this._rotated.z += this._pivotBackTranslation.z;
  61545. 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;
  61546. 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;
  61547. 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;
  61548. if (this._computeBoundingBox) {
  61549. if (this._positions32[idx] < this._minimum.x) {
  61550. this._minimum.x = this._positions32[idx];
  61551. }
  61552. if (this._positions32[idx] > this._maximum.x) {
  61553. this._maximum.x = this._positions32[idx];
  61554. }
  61555. if (this._positions32[idx + 1] < this._minimum.y) {
  61556. this._minimum.y = this._positions32[idx + 1];
  61557. }
  61558. if (this._positions32[idx + 1] > this._maximum.y) {
  61559. this._maximum.y = this._positions32[idx + 1];
  61560. }
  61561. if (this._positions32[idx + 2] < this._minimum.z) {
  61562. this._minimum.z = this._positions32[idx + 2];
  61563. }
  61564. if (this._positions32[idx + 2] > this._maximum.z) {
  61565. this._maximum.z = this._positions32[idx + 2];
  61566. }
  61567. }
  61568. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  61569. if (!this._computeParticleVertex) {
  61570. this._normal.x = this._fixedNormal32[idx];
  61571. this._normal.y = this._fixedNormal32[idx + 1];
  61572. this._normal.z = this._fixedNormal32[idx + 2];
  61573. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  61574. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  61575. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  61576. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  61577. 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;
  61578. 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;
  61579. }
  61580. if (this._computeParticleColor && this._particle.color) {
  61581. this._colors32[colidx] = this._particle.color.r;
  61582. this._colors32[colidx + 1] = this._particle.color.g;
  61583. this._colors32[colidx + 2] = this._particle.color.b;
  61584. this._colors32[colidx + 3] = this._particle.color.a;
  61585. }
  61586. if (this._computeParticleTexture) {
  61587. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61588. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61589. }
  61590. }
  61591. }
  61592. // particle just set invisible : scaled to zero and positioned at the origin
  61593. else {
  61594. this._particle._stillInvisible = true; // mark the particle as invisible
  61595. for (pt = 0; pt < this._shape.length; pt++) {
  61596. idx = index + pt * 3;
  61597. colidx = colorIndex + pt * 4;
  61598. uvidx = uvIndex + pt * 2;
  61599. this._positions32[idx] = 0.0;
  61600. this._positions32[idx + 1] = 0.0;
  61601. this._positions32[idx + 2] = 0.0;
  61602. this._normals32[idx] = 0.0;
  61603. this._normals32[idx + 1] = 0.0;
  61604. this._normals32[idx + 2] = 0.0;
  61605. if (this._computeParticleColor && this._particle.color) {
  61606. this._colors32[colidx] = this._particle.color.r;
  61607. this._colors32[colidx + 1] = this._particle.color.g;
  61608. this._colors32[colidx + 2] = this._particle.color.b;
  61609. this._colors32[colidx + 3] = this._particle.color.a;
  61610. }
  61611. if (this._computeParticleTexture) {
  61612. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61613. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61614. }
  61615. }
  61616. }
  61617. // if the particle intersections must be computed : update the bbInfo
  61618. if (this._particlesIntersect) {
  61619. var bInfo = this._particle._boundingInfo;
  61620. var bBox = bInfo.boundingBox;
  61621. var bSphere = bInfo.boundingSphere;
  61622. if (!this._bSphereOnly) {
  61623. // place, scale and rotate the particle bbox within the SPS local system, then update it
  61624. for (var b = 0; b < bBox.vectors.length; b++) {
  61625. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  61626. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  61627. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  61628. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61629. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61630. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61631. 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;
  61632. 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;
  61633. 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;
  61634. }
  61635. bBox._update(this.mesh._worldMatrix);
  61636. }
  61637. // place and scale the particle bouding sphere in the SPS local system, then update it
  61638. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  61639. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  61640. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  61641. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  61642. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  61643. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  61644. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  61645. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  61646. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  61647. 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));
  61648. bSphere._update(this.mesh._worldMatrix);
  61649. }
  61650. // increment indexes for the next particle
  61651. index = idx + 3;
  61652. colorIndex = colidx + 4;
  61653. uvIndex = uvidx + 2;
  61654. }
  61655. // if the VBO must be updated
  61656. if (update) {
  61657. if (this._computeParticleColor) {
  61658. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  61659. }
  61660. if (this._computeParticleTexture) {
  61661. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  61662. }
  61663. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61664. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  61665. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  61666. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  61667. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  61668. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  61669. for (var i = 0; i < this._normals32.length; i++) {
  61670. this._fixedNormal32[i] = this._normals32[i];
  61671. }
  61672. }
  61673. if (!this.mesh.areNormalsFrozen) {
  61674. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  61675. }
  61676. }
  61677. if (this._depthSort && this._depthSortParticles) {
  61678. this.depthSortedParticles.sort(this._depthSortFunction);
  61679. var dspl = this.depthSortedParticles.length;
  61680. var sorted = 0;
  61681. var lind = 0;
  61682. var sind = 0;
  61683. var sid = 0;
  61684. for (sorted = 0; sorted < dspl; sorted++) {
  61685. lind = this.depthSortedParticles[sorted].indicesLength;
  61686. sind = this.depthSortedParticles[sorted].ind;
  61687. for (var i = 0; i < lind; i++) {
  61688. this._indices32[sid] = this._indices[sind + i];
  61689. sid++;
  61690. }
  61691. }
  61692. this.mesh.updateIndices(this._indices32);
  61693. }
  61694. }
  61695. if (this._computeBoundingBox) {
  61696. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  61697. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  61698. }
  61699. this.afterUpdateParticles(start, end, update);
  61700. return this;
  61701. };
  61702. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  61703. this._halfroll = this._roll * 0.5;
  61704. this._halfpitch = this._pitch * 0.5;
  61705. this._halfyaw = this._yaw * 0.5;
  61706. this._sinRoll = Math.sin(this._halfroll);
  61707. this._cosRoll = Math.cos(this._halfroll);
  61708. this._sinPitch = Math.sin(this._halfpitch);
  61709. this._cosPitch = Math.cos(this._halfpitch);
  61710. this._sinYaw = Math.sin(this._halfyaw);
  61711. this._cosYaw = Math.cos(this._halfyaw);
  61712. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  61713. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  61714. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  61715. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  61716. };
  61717. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  61718. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  61719. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  61720. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  61721. this._rotMatrix.m[3] = 0;
  61722. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  61723. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  61724. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  61725. this._rotMatrix.m[7] = 0;
  61726. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  61727. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  61728. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  61729. this._rotMatrix.m[11] = 0;
  61730. this._rotMatrix.m[12] = 0;
  61731. this._rotMatrix.m[13] = 0;
  61732. this._rotMatrix.m[14] = 0;
  61733. this._rotMatrix.m[15] = 1.0;
  61734. };
  61735. /**
  61736. * Disposes the SPS.
  61737. */
  61738. SolidParticleSystem.prototype.dispose = function () {
  61739. this.mesh.dispose();
  61740. this.vars = null;
  61741. // drop references to internal big arrays for the GC
  61742. this._positions = null;
  61743. this._indices = null;
  61744. this._normals = null;
  61745. this._uvs = null;
  61746. this._colors = null;
  61747. this._indices32 = null;
  61748. this._positions32 = null;
  61749. this._normals32 = null;
  61750. this._fixedNormal32 = null;
  61751. this._uvs32 = null;
  61752. this._colors32 = null;
  61753. this.pickedParticles = null;
  61754. };
  61755. /**
  61756. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  61757. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61758. * @returns the SPS.
  61759. */
  61760. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  61761. if (!this._isVisibilityBoxLocked) {
  61762. this.mesh.refreshBoundingInfo();
  61763. }
  61764. return this;
  61765. };
  61766. /**
  61767. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  61768. * @param size the size (float) of the visibility box
  61769. * note : this doesn't lock the SPS mesh bounding box.
  61770. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61771. */
  61772. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  61773. var vis = size / 2;
  61774. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  61775. };
  61776. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  61777. /**
  61778. * Gets whether the SPS as always visible or not
  61779. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61780. */
  61781. get: function () {
  61782. return this._alwaysVisible;
  61783. },
  61784. /**
  61785. * Sets the SPS as always visible or not
  61786. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61787. */
  61788. set: function (val) {
  61789. this._alwaysVisible = val;
  61790. this.mesh.alwaysSelectAsActiveMesh = val;
  61791. },
  61792. enumerable: true,
  61793. configurable: true
  61794. });
  61795. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  61796. /**
  61797. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61798. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61799. */
  61800. get: function () {
  61801. return this._isVisibilityBoxLocked;
  61802. },
  61803. /**
  61804. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61805. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61806. */
  61807. set: function (val) {
  61808. this._isVisibilityBoxLocked = val;
  61809. var boundingInfo = this.mesh.getBoundingInfo();
  61810. boundingInfo.isLocked = val;
  61811. },
  61812. enumerable: true,
  61813. configurable: true
  61814. });
  61815. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  61816. /**
  61817. * Gets if `setParticles()` computes the particle rotations or not.
  61818. * Default value : true. The SPS is faster when it's set to false.
  61819. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61820. */
  61821. get: function () {
  61822. return this._computeParticleRotation;
  61823. },
  61824. /**
  61825. * Tells to `setParticles()` to compute the particle rotations or not.
  61826. * Default value : true. The SPS is faster when it's set to false.
  61827. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61828. */
  61829. set: function (val) {
  61830. this._computeParticleRotation = val;
  61831. },
  61832. enumerable: true,
  61833. configurable: true
  61834. });
  61835. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  61836. /**
  61837. * Gets if `setParticles()` computes the particle colors or not.
  61838. * Default value : true. The SPS is faster when it's set to false.
  61839. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61840. */
  61841. get: function () {
  61842. return this._computeParticleColor;
  61843. },
  61844. /**
  61845. * Tells to `setParticles()` to compute the particle colors or not.
  61846. * Default value : true. The SPS is faster when it's set to false.
  61847. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61848. */
  61849. set: function (val) {
  61850. this._computeParticleColor = val;
  61851. },
  61852. enumerable: true,
  61853. configurable: true
  61854. });
  61855. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  61856. /**
  61857. * Gets if `setParticles()` computes the particle textures or not.
  61858. * Default value : true. The SPS is faster when it's set to false.
  61859. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  61860. */
  61861. get: function () {
  61862. return this._computeParticleTexture;
  61863. },
  61864. set: function (val) {
  61865. this._computeParticleTexture = val;
  61866. },
  61867. enumerable: true,
  61868. configurable: true
  61869. });
  61870. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  61871. /**
  61872. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  61873. * Default value : false. The SPS is faster when it's set to false.
  61874. * Note : the particle custom vertex positions aren't stored values.
  61875. */
  61876. get: function () {
  61877. return this._computeParticleVertex;
  61878. },
  61879. /**
  61880. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  61881. * Default value : false. The SPS is faster when it's set to false.
  61882. * Note : the particle custom vertex positions aren't stored values.
  61883. */
  61884. set: function (val) {
  61885. this._computeParticleVertex = val;
  61886. },
  61887. enumerable: true,
  61888. configurable: true
  61889. });
  61890. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  61891. /**
  61892. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  61893. */
  61894. get: function () {
  61895. return this._computeBoundingBox;
  61896. },
  61897. /**
  61898. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  61899. */
  61900. set: function (val) {
  61901. this._computeBoundingBox = val;
  61902. },
  61903. enumerable: true,
  61904. configurable: true
  61905. });
  61906. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  61907. /**
  61908. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  61909. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  61910. * Default : `true`
  61911. */
  61912. get: function () {
  61913. return this._depthSortParticles;
  61914. },
  61915. /**
  61916. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  61917. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  61918. * Default : `true`
  61919. */
  61920. set: function (val) {
  61921. this._depthSortParticles = val;
  61922. },
  61923. enumerable: true,
  61924. configurable: true
  61925. });
  61926. // =======================================================================
  61927. // Particle behavior logic
  61928. // these following methods may be overwritten by the user to fit his needs
  61929. /**
  61930. * This function does nothing. It may be overwritten to set all the particle first values.
  61931. * The SPS doesn't call this function, you may have to call it by your own.
  61932. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61933. */
  61934. SolidParticleSystem.prototype.initParticles = function () {
  61935. };
  61936. /**
  61937. * This function does nothing. It may be overwritten to recycle a particle.
  61938. * The SPS doesn't call this function, you may have to call it by your own.
  61939. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61940. * @param particle The particle to recycle
  61941. * @returns the recycled particle
  61942. */
  61943. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  61944. return particle;
  61945. };
  61946. /**
  61947. * Updates a particle : this function should be overwritten by the user.
  61948. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  61949. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61950. * @example : just set a particle position or velocity and recycle conditions
  61951. * @param particle The particle to update
  61952. * @returns the updated particle
  61953. */
  61954. SolidParticleSystem.prototype.updateParticle = function (particle) {
  61955. return particle;
  61956. };
  61957. /**
  61958. * Updates a vertex of a particle : it can be overwritten by the user.
  61959. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  61960. * @param particle the current particle
  61961. * @param vertex the current index of the current particle
  61962. * @param pt the index of the current vertex in the particle shape
  61963. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  61964. * @example : just set a vertex particle position
  61965. * @returns the updated vertex
  61966. */
  61967. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  61968. return vertex;
  61969. };
  61970. /**
  61971. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  61972. * This does nothing and may be overwritten by the user.
  61973. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61974. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61975. * @param update the boolean update value actually passed to setParticles()
  61976. */
  61977. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  61978. };
  61979. /**
  61980. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  61981. * This will be passed three parameters.
  61982. * This does nothing and may be overwritten by the user.
  61983. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61984. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61985. * @param update the boolean update value actually passed to setParticles()
  61986. */
  61987. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  61988. };
  61989. return SolidParticleSystem;
  61990. }());
  61991. BABYLON.SolidParticleSystem = SolidParticleSystem;
  61992. })(BABYLON || (BABYLON = {}));
  61993. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  61994. var BABYLON;
  61995. (function (BABYLON) {
  61996. /**
  61997. * Class containing static functions to help procedurally build meshes
  61998. */
  61999. var MeshBuilder = /** @class */ (function () {
  62000. function MeshBuilder() {
  62001. }
  62002. MeshBuilder.updateSideOrientation = function (orientation) {
  62003. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  62004. return BABYLON.Mesh.DOUBLESIDE;
  62005. }
  62006. if (orientation === undefined || orientation === null) {
  62007. return BABYLON.Mesh.FRONTSIDE;
  62008. }
  62009. return orientation;
  62010. };
  62011. /**
  62012. * Creates a box mesh
  62013. * * The parameter `size` sets the size (float) of each box side (default 1)
  62014. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  62015. * * 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)
  62016. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62017. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62018. * * 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
  62019. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62020. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  62021. * @param name defines the name of the mesh
  62022. * @param options defines the options used to create the mesh
  62023. * @param scene defines the hosting scene
  62024. * @returns the box mesh
  62025. */
  62026. MeshBuilder.CreateBox = function (name, options, scene) {
  62027. if (scene === void 0) { scene = null; }
  62028. var box = new BABYLON.Mesh(name, scene);
  62029. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62030. box._originalBuilderSideOrientation = options.sideOrientation;
  62031. var vertexData = BABYLON.VertexData.CreateBox(options);
  62032. vertexData.applyToMesh(box, options.updatable);
  62033. return box;
  62034. };
  62035. /**
  62036. * Creates a sphere mesh
  62037. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  62038. * * 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`)
  62039. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  62040. * * 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
  62041. * * 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)
  62042. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62043. * * 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
  62044. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62045. * @param name defines the name of the mesh
  62046. * @param options defines the options used to create the mesh
  62047. * @param scene defines the hosting scene
  62048. * @returns the sphere mesh
  62049. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  62050. */
  62051. MeshBuilder.CreateSphere = function (name, options, scene) {
  62052. var sphere = new BABYLON.Mesh(name, scene);
  62053. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62054. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62055. var vertexData = BABYLON.VertexData.CreateSphere(options);
  62056. vertexData.applyToMesh(sphere, options.updatable);
  62057. return sphere;
  62058. };
  62059. /**
  62060. * Creates a plane polygonal mesh. By default, this is a disc
  62061. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  62062. * * 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
  62063. * * 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
  62064. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62065. * * 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
  62066. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62067. * @param name defines the name of the mesh
  62068. * @param options defines the options used to create the mesh
  62069. * @param scene defines the hosting scene
  62070. * @returns the plane polygonal mesh
  62071. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  62072. */
  62073. MeshBuilder.CreateDisc = function (name, options, scene) {
  62074. if (scene === void 0) { scene = null; }
  62075. var disc = new BABYLON.Mesh(name, scene);
  62076. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62077. disc._originalBuilderSideOrientation = options.sideOrientation;
  62078. var vertexData = BABYLON.VertexData.CreateDisc(options);
  62079. vertexData.applyToMesh(disc, options.updatable);
  62080. return disc;
  62081. };
  62082. /**
  62083. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  62084. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  62085. * * 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`)
  62086. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  62087. * * 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
  62088. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62089. * * 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
  62090. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62091. * @param name defines the name of the mesh
  62092. * @param options defines the options used to create the mesh
  62093. * @param scene defines the hosting scene
  62094. * @returns the icosahedron mesh
  62095. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  62096. */
  62097. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  62098. var sphere = new BABYLON.Mesh(name, scene);
  62099. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62100. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62101. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  62102. vertexData.applyToMesh(sphere, options.updatable);
  62103. return sphere;
  62104. };
  62105. ;
  62106. /**
  62107. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62108. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  62109. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  62110. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  62111. * * 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
  62112. * * 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
  62113. * * 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
  62114. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62115. * * 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
  62116. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62117. * * 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
  62118. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  62119. * * 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
  62120. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  62121. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62122. * @param name defines the name of the mesh
  62123. * @param options defines the options used to create the mesh
  62124. * @param scene defines the hosting scene
  62125. * @returns the ribbon mesh
  62126. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  62127. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62128. */
  62129. MeshBuilder.CreateRibbon = function (name, options, scene) {
  62130. if (scene === void 0) { scene = null; }
  62131. var pathArray = options.pathArray;
  62132. var closeArray = options.closeArray;
  62133. var closePath = options.closePath;
  62134. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62135. var instance = options.instance;
  62136. var updatable = options.updatable;
  62137. if (instance) { // existing ribbon instance update
  62138. // positionFunction : ribbon case
  62139. // only pathArray and sideOrientation parameters are taken into account for positions update
  62140. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  62141. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  62142. var positionFunction = function (positions) {
  62143. var minlg = pathArray[0].length;
  62144. var i = 0;
  62145. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  62146. for (var si = 1; si <= ns; si++) {
  62147. for (var p = 0; p < pathArray.length; p++) {
  62148. var path = pathArray[p];
  62149. var l = path.length;
  62150. minlg = (minlg < l) ? minlg : l;
  62151. var j = 0;
  62152. while (j < minlg) {
  62153. positions[i] = path[j].x;
  62154. positions[i + 1] = path[j].y;
  62155. positions[i + 2] = path[j].z;
  62156. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  62157. BABYLON.Tmp.Vector3[0].x = path[j].x;
  62158. }
  62159. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  62160. BABYLON.Tmp.Vector3[1].x = path[j].x;
  62161. }
  62162. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  62163. BABYLON.Tmp.Vector3[0].y = path[j].y;
  62164. }
  62165. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  62166. BABYLON.Tmp.Vector3[1].y = path[j].y;
  62167. }
  62168. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  62169. BABYLON.Tmp.Vector3[0].z = path[j].z;
  62170. }
  62171. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  62172. BABYLON.Tmp.Vector3[1].z = path[j].z;
  62173. }
  62174. j++;
  62175. i += 3;
  62176. }
  62177. if (instance._closePath) {
  62178. positions[i] = path[0].x;
  62179. positions[i + 1] = path[0].y;
  62180. positions[i + 2] = path[0].z;
  62181. i += 3;
  62182. }
  62183. }
  62184. }
  62185. };
  62186. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62187. positionFunction(positions);
  62188. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  62189. instance._boundingInfo.update(instance._worldMatrix);
  62190. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62191. if (options.colors) {
  62192. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62193. for (var c = 0; c < options.colors.length; c++) {
  62194. colors[c * 4] = options.colors[c].r;
  62195. colors[c * 4 + 1] = options.colors[c].g;
  62196. colors[c * 4 + 2] = options.colors[c].b;
  62197. colors[c * 4 + 3] = options.colors[c].a;
  62198. }
  62199. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  62200. }
  62201. if (options.uvs) {
  62202. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62203. for (var i = 0; i < options.uvs.length; i++) {
  62204. uvs[i * 2] = options.uvs[i].x;
  62205. uvs[i * 2 + 1] = options.uvs[i].y;
  62206. }
  62207. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  62208. }
  62209. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  62210. var indices = instance.getIndices();
  62211. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62212. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  62213. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  62214. if (instance._closePath) {
  62215. var indexFirst = 0;
  62216. var indexLast = 0;
  62217. for (var p = 0; p < pathArray.length; p++) {
  62218. indexFirst = instance._idx[p] * 3;
  62219. if (p + 1 < pathArray.length) {
  62220. indexLast = (instance._idx[p + 1] - 1) * 3;
  62221. }
  62222. else {
  62223. indexLast = normals.length - 3;
  62224. }
  62225. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  62226. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  62227. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  62228. normals[indexLast] = normals[indexFirst];
  62229. normals[indexLast + 1] = normals[indexFirst + 1];
  62230. normals[indexLast + 2] = normals[indexFirst + 2];
  62231. }
  62232. }
  62233. if (!(instance.areNormalsFrozen)) {
  62234. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  62235. }
  62236. }
  62237. return instance;
  62238. }
  62239. else { // new ribbon creation
  62240. var ribbon = new BABYLON.Mesh(name, scene);
  62241. ribbon._originalBuilderSideOrientation = sideOrientation;
  62242. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  62243. if (closePath) {
  62244. ribbon._idx = vertexData._idx;
  62245. }
  62246. ribbon._closePath = closePath;
  62247. ribbon._closeArray = closeArray;
  62248. vertexData.applyToMesh(ribbon, updatable);
  62249. return ribbon;
  62250. }
  62251. };
  62252. /**
  62253. * Creates a cylinder or a cone mesh
  62254. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  62255. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  62256. * * 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.
  62257. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  62258. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  62259. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  62260. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  62261. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  62262. * * 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).
  62263. * * 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
  62264. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  62265. * * 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
  62266. * * 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.
  62267. * * If `enclose` is false, a ring surface is one element.
  62268. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  62269. * * 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
  62270. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62271. * * 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
  62272. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62273. * @param name defines the name of the mesh
  62274. * @param options defines the options used to create the mesh
  62275. * @param scene defines the hosting scene
  62276. * @returns the cylinder mesh
  62277. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  62278. */
  62279. MeshBuilder.CreateCylinder = function (name, options, scene) {
  62280. var cylinder = new BABYLON.Mesh(name, scene);
  62281. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62282. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  62283. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  62284. vertexData.applyToMesh(cylinder, options.updatable);
  62285. return cylinder;
  62286. };
  62287. /**
  62288. * Creates a torus mesh
  62289. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  62290. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  62291. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  62292. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62293. * * 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
  62294. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62295. * @param name defines the name of the mesh
  62296. * @param options defines the options used to create the mesh
  62297. * @param scene defines the hosting scene
  62298. * @returns the torus mesh
  62299. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  62300. */
  62301. MeshBuilder.CreateTorus = function (name, options, scene) {
  62302. var torus = new BABYLON.Mesh(name, scene);
  62303. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62304. torus._originalBuilderSideOrientation = options.sideOrientation;
  62305. var vertexData = BABYLON.VertexData.CreateTorus(options);
  62306. vertexData.applyToMesh(torus, options.updatable);
  62307. return torus;
  62308. };
  62309. /**
  62310. * Creates a torus knot mesh
  62311. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  62312. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  62313. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  62314. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  62315. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62316. * * 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
  62317. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62318. * @param name defines the name of the mesh
  62319. * @param options defines the options used to create the mesh
  62320. * @param scene defines the hosting scene
  62321. * @returns the torus knot mesh
  62322. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  62323. */
  62324. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  62325. var torusKnot = new BABYLON.Mesh(name, scene);
  62326. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62327. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  62328. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  62329. vertexData.applyToMesh(torusKnot, options.updatable);
  62330. return torusKnot;
  62331. };
  62332. /**
  62333. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  62334. * * 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
  62335. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  62336. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  62337. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  62338. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  62339. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  62340. * * 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
  62341. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  62342. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62343. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  62344. * @param name defines the name of the new line system
  62345. * @param options defines the options used to create the line system
  62346. * @param scene defines the hosting scene
  62347. * @returns a new line system mesh
  62348. */
  62349. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  62350. var instance = options.instance;
  62351. var lines = options.lines;
  62352. var colors = options.colors;
  62353. if (instance) { // lines update
  62354. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62355. var vertexColor;
  62356. var lineColors;
  62357. if (colors) {
  62358. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62359. }
  62360. var i = 0;
  62361. var c = 0;
  62362. for (var l = 0; l < lines.length; l++) {
  62363. var points = lines[l];
  62364. for (var p = 0; p < points.length; p++) {
  62365. positions[i] = points[p].x;
  62366. positions[i + 1] = points[p].y;
  62367. positions[i + 2] = points[p].z;
  62368. if (colors && vertexColor) {
  62369. lineColors = colors[l];
  62370. vertexColor[c] = lineColors[p].r;
  62371. vertexColor[c + 1] = lineColors[p].g;
  62372. vertexColor[c + 2] = lineColors[p].b;
  62373. vertexColor[c + 3] = lineColors[p].a;
  62374. c += 4;
  62375. }
  62376. i += 3;
  62377. }
  62378. }
  62379. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62380. if (colors && vertexColor) {
  62381. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  62382. }
  62383. return instance;
  62384. }
  62385. // line system creation
  62386. var useVertexColor = (colors) ? true : false;
  62387. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  62388. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  62389. vertexData.applyToMesh(lineSystem, options.updatable);
  62390. return lineSystem;
  62391. };
  62392. /**
  62393. * Creates a line mesh
  62394. * 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
  62395. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62396. * * The parameter `points` is an array successive Vector3
  62397. * * 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
  62398. * * The optional parameter `colors` is an array of successive Color4, one per line point
  62399. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  62400. * * When updating an instance, remember that only point positions can change, not the number of points
  62401. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62402. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  62403. * @param name defines the name of the new line system
  62404. * @param options defines the options used to create the line system
  62405. * @param scene defines the hosting scene
  62406. * @returns a new line mesh
  62407. */
  62408. MeshBuilder.CreateLines = function (name, options, scene) {
  62409. if (scene === void 0) { scene = null; }
  62410. var colors = (options.colors) ? [options.colors] : null;
  62411. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  62412. return lines;
  62413. };
  62414. /**
  62415. * Creates a dashed line mesh
  62416. * * 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
  62417. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62418. * * The parameter `points` is an array successive Vector3
  62419. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  62420. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  62421. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  62422. * * 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
  62423. * * When updating an instance, remember that only point positions can change, not the number of points
  62424. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62425. * @param name defines the name of the mesh
  62426. * @param options defines the options used to create the mesh
  62427. * @param scene defines the hosting scene
  62428. * @returns the dashed line mesh
  62429. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  62430. */
  62431. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  62432. if (scene === void 0) { scene = null; }
  62433. var points = options.points;
  62434. var instance = options.instance;
  62435. var gapSize = options.gapSize || 1;
  62436. var dashSize = options.dashSize || 3;
  62437. if (instance) { // dashed lines update
  62438. var positionFunction = function (positions) {
  62439. var curvect = BABYLON.Vector3.Zero();
  62440. var nbSeg = positions.length / 6;
  62441. var lg = 0;
  62442. var nb = 0;
  62443. var shft = 0;
  62444. var dashshft = 0;
  62445. var curshft = 0;
  62446. var p = 0;
  62447. var i = 0;
  62448. var j = 0;
  62449. for (i = 0; i < points.length - 1; i++) {
  62450. points[i + 1].subtractToRef(points[i], curvect);
  62451. lg += curvect.length();
  62452. }
  62453. shft = lg / nbSeg;
  62454. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  62455. for (i = 0; i < points.length - 1; i++) {
  62456. points[i + 1].subtractToRef(points[i], curvect);
  62457. nb = Math.floor(curvect.length() / shft);
  62458. curvect.normalize();
  62459. j = 0;
  62460. while (j < nb && p < positions.length) {
  62461. curshft = shft * j;
  62462. positions[p] = points[i].x + curshft * curvect.x;
  62463. positions[p + 1] = points[i].y + curshft * curvect.y;
  62464. positions[p + 2] = points[i].z + curshft * curvect.z;
  62465. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  62466. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  62467. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  62468. p += 6;
  62469. j++;
  62470. }
  62471. }
  62472. while (p < positions.length) {
  62473. positions[p] = points[i].x;
  62474. positions[p + 1] = points[i].y;
  62475. positions[p + 2] = points[i].z;
  62476. p += 3;
  62477. }
  62478. };
  62479. instance.updateMeshPositions(positionFunction, false);
  62480. return instance;
  62481. }
  62482. // dashed lines creation
  62483. var dashedLines = new BABYLON.LinesMesh(name, scene);
  62484. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  62485. vertexData.applyToMesh(dashedLines, options.updatable);
  62486. dashedLines.dashSize = dashSize;
  62487. dashedLines.gapSize = gapSize;
  62488. return dashedLines;
  62489. };
  62490. /**
  62491. * 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.
  62492. * * 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.
  62493. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62494. * * 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.
  62495. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  62496. * * 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
  62497. * * 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
  62498. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  62499. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62500. * * 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
  62501. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  62502. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62503. * @param name defines the name of the mesh
  62504. * @param options defines the options used to create the mesh
  62505. * @param scene defines the hosting scene
  62506. * @returns the extruded shape mesh
  62507. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62508. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62509. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62510. */
  62511. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  62512. if (scene === void 0) { scene = null; }
  62513. var path = options.path;
  62514. var shape = options.shape;
  62515. var scale = options.scale || 1;
  62516. var rotation = options.rotation || 0;
  62517. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62518. var updatable = options.updatable;
  62519. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62520. var instance = options.instance || null;
  62521. var invertUV = options.invertUV || false;
  62522. 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);
  62523. };
  62524. /**
  62525. * Creates an custom extruded shape mesh.
  62526. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  62527. * * 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.
  62528. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62529. * * 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
  62530. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  62531. * * 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
  62532. * * It must returns a float value that will be the scale value applied to the shape on each path point
  62533. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  62534. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  62535. * * 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
  62536. * * 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
  62537. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  62538. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62539. * * 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
  62540. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62541. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62542. * @param name defines the name of the mesh
  62543. * @param options defines the options used to create the mesh
  62544. * @param scene defines the hosting scene
  62545. * @returns the custom extruded shape mesh
  62546. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  62547. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62548. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62549. */
  62550. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  62551. var path = options.path;
  62552. var shape = options.shape;
  62553. var scaleFunction = options.scaleFunction || (function () { return 1; });
  62554. var rotationFunction = options.rotationFunction || (function () { return 0; });
  62555. var ribbonCloseArray = options.ribbonCloseArray || false;
  62556. var ribbonClosePath = options.ribbonClosePath || false;
  62557. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62558. var updatable = options.updatable;
  62559. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62560. var instance = options.instance;
  62561. var invertUV = options.invertUV || false;
  62562. 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);
  62563. };
  62564. /**
  62565. * Creates lathe mesh.
  62566. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  62567. * * 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
  62568. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  62569. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  62570. * * 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
  62571. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  62572. * * 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
  62573. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62574. * * 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
  62575. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62576. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62577. * @param name defines the name of the mesh
  62578. * @param options defines the options used to create the mesh
  62579. * @param scene defines the hosting scene
  62580. * @returns the lathe mesh
  62581. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  62582. */
  62583. MeshBuilder.CreateLathe = function (name, options, scene) {
  62584. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  62585. var closed = (options.closed === undefined) ? true : options.closed;
  62586. var shape = options.shape;
  62587. var radius = options.radius || 1;
  62588. var tessellation = options.tessellation || 64;
  62589. var updatable = options.updatable;
  62590. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62591. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62592. var pi2 = Math.PI * 2;
  62593. var paths = new Array();
  62594. var invertUV = options.invertUV || false;
  62595. var i = 0;
  62596. var p = 0;
  62597. var step = pi2 / tessellation * arc;
  62598. var rotated;
  62599. var path = new Array();
  62600. for (i = 0; i <= tessellation; i++) {
  62601. var path = [];
  62602. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  62603. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  62604. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  62605. }
  62606. for (p = 0; p < shape.length; p++) {
  62607. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  62608. path.push(rotated);
  62609. }
  62610. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  62611. 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));
  62612. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  62613. }
  62614. paths.push(path);
  62615. }
  62616. // lathe ribbon
  62617. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62618. return lathe;
  62619. };
  62620. /**
  62621. * Creates a plane mesh
  62622. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  62623. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  62624. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  62625. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62626. * * 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
  62627. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62628. * @param name defines the name of the mesh
  62629. * @param options defines the options used to create the mesh
  62630. * @param scene defines the hosting scene
  62631. * @returns the plane mesh
  62632. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62633. */
  62634. MeshBuilder.CreatePlane = function (name, options, scene) {
  62635. var plane = new BABYLON.Mesh(name, scene);
  62636. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62637. plane._originalBuilderSideOrientation = options.sideOrientation;
  62638. var vertexData = BABYLON.VertexData.CreatePlane(options);
  62639. vertexData.applyToMesh(plane, options.updatable);
  62640. if (options.sourcePlane) {
  62641. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  62642. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  62643. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  62644. plane.rotate(vectorProduct, product);
  62645. }
  62646. return plane;
  62647. };
  62648. /**
  62649. * Creates a ground mesh
  62650. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  62651. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  62652. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62653. * @param name defines the name of the mesh
  62654. * @param options defines the options used to create the mesh
  62655. * @param scene defines the hosting scene
  62656. * @returns the ground mesh
  62657. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62658. */
  62659. MeshBuilder.CreateGround = function (name, options, scene) {
  62660. var ground = new BABYLON.GroundMesh(name, scene);
  62661. ground._setReady(false);
  62662. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  62663. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  62664. ground._width = options.width || 1;
  62665. ground._height = options.height || 1;
  62666. ground._maxX = ground._width / 2;
  62667. ground._maxZ = ground._height / 2;
  62668. ground._minX = -ground._maxX;
  62669. ground._minZ = -ground._maxZ;
  62670. var vertexData = BABYLON.VertexData.CreateGround(options);
  62671. vertexData.applyToMesh(ground, options.updatable);
  62672. ground._setReady(true);
  62673. return ground;
  62674. };
  62675. /**
  62676. * Creates a tiled ground mesh
  62677. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  62678. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  62679. * * 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
  62680. * * 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
  62681. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62682. * @param name defines the name of the mesh
  62683. * @param options defines the options used to create the mesh
  62684. * @param scene defines the hosting scene
  62685. * @returns the tiled ground mesh
  62686. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  62687. */
  62688. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  62689. var tiledGround = new BABYLON.Mesh(name, scene);
  62690. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  62691. vertexData.applyToMesh(tiledGround, options.updatable);
  62692. return tiledGround;
  62693. };
  62694. /**
  62695. * Creates a ground mesh from a height map
  62696. * * The parameter `url` sets the URL of the height map image resource.
  62697. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  62698. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  62699. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  62700. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  62701. * * 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.
  62702. * * 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).
  62703. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62704. * @param name defines the name of the mesh
  62705. * @param url defines the url to the height map
  62706. * @param options defines the options used to create the mesh
  62707. * @param scene defines the hosting scene
  62708. * @returns the ground mesh
  62709. * @see http://doc.babylonjs.com/babylon101/height_map
  62710. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  62711. */
  62712. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  62713. var width = options.width || 10.0;
  62714. var height = options.height || 10.0;
  62715. var subdivisions = options.subdivisions || 1 | 0;
  62716. var minHeight = options.minHeight || 0.0;
  62717. var maxHeight = options.maxHeight || 1.0;
  62718. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  62719. var updatable = options.updatable;
  62720. var onReady = options.onReady;
  62721. var ground = new BABYLON.GroundMesh(name, scene);
  62722. ground._subdivisionsX = subdivisions;
  62723. ground._subdivisionsY = subdivisions;
  62724. ground._width = width;
  62725. ground._height = height;
  62726. ground._maxX = ground._width / 2.0;
  62727. ground._maxZ = ground._height / 2.0;
  62728. ground._minX = -ground._maxX;
  62729. ground._minZ = -ground._maxZ;
  62730. ground._setReady(false);
  62731. var onload = function (img) {
  62732. // Getting height map data
  62733. var canvas = document.createElement("canvas");
  62734. var context = canvas.getContext("2d");
  62735. if (!context) {
  62736. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  62737. }
  62738. if (scene.isDisposed) {
  62739. return;
  62740. }
  62741. var bufferWidth = img.width;
  62742. var bufferHeight = img.height;
  62743. canvas.width = bufferWidth;
  62744. canvas.height = bufferHeight;
  62745. context.drawImage(img, 0, 0);
  62746. // Create VertexData from map data
  62747. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  62748. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  62749. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  62750. width: width, height: height,
  62751. subdivisions: subdivisions,
  62752. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  62753. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  62754. });
  62755. vertexData.applyToMesh(ground, updatable);
  62756. //execute ready callback, if set
  62757. if (onReady) {
  62758. onReady(ground);
  62759. }
  62760. ground._setReady(true);
  62761. };
  62762. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  62763. return ground;
  62764. };
  62765. /**
  62766. * Creates a polygon mesh
  62767. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  62768. * * 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
  62769. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62770. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62771. * * 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)
  62772. * * Remember you can only change the shape positions, not their number when updating a polygon
  62773. * @param name defines the name of the mesh
  62774. * @param options defines the options used to create the mesh
  62775. * @param scene defines the hosting scene
  62776. * @returns the polygon mesh
  62777. */
  62778. MeshBuilder.CreatePolygon = function (name, options, scene) {
  62779. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62780. var shape = options.shape;
  62781. var holes = options.holes || [];
  62782. var depth = options.depth || 0;
  62783. var contours = [];
  62784. var hole = [];
  62785. for (var i = 0; i < shape.length; i++) {
  62786. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  62787. }
  62788. var epsilon = 0.00000001;
  62789. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  62790. contours.pop();
  62791. }
  62792. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  62793. for (var hNb = 0; hNb < holes.length; hNb++) {
  62794. hole = [];
  62795. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  62796. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  62797. }
  62798. polygonTriangulation.addHole(hole);
  62799. }
  62800. var polygon = polygonTriangulation.build(options.updatable, depth);
  62801. polygon._originalBuilderSideOrientation = options.sideOrientation;
  62802. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  62803. vertexData.applyToMesh(polygon, options.updatable);
  62804. return polygon;
  62805. };
  62806. ;
  62807. /**
  62808. * Creates an extruded polygon mesh, with depth in the Y direction.
  62809. * * 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)
  62810. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62811. * @param name defines the name of the mesh
  62812. * @param options defines the options used to create the mesh
  62813. * @param scene defines the hosting scene
  62814. * @returns the polygon mesh
  62815. */
  62816. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  62817. return MeshBuilder.CreatePolygon(name, options, scene);
  62818. };
  62819. ;
  62820. /**
  62821. * Creates a tube mesh.
  62822. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62823. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  62824. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  62825. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  62826. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  62827. * * 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)
  62828. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  62829. * * 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
  62830. * * 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
  62831. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62832. * * 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
  62833. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62834. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62835. * @param name defines the name of the mesh
  62836. * @param options defines the options used to create the mesh
  62837. * @param scene defines the hosting scene
  62838. * @returns the tube mesh
  62839. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62840. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  62841. */
  62842. MeshBuilder.CreateTube = function (name, options, scene) {
  62843. var path = options.path;
  62844. var instance = options.instance;
  62845. var radius = 1.0;
  62846. if (instance) {
  62847. radius = instance.radius;
  62848. }
  62849. if (options.radius !== undefined) {
  62850. radius = options.radius;
  62851. }
  62852. ;
  62853. var tessellation = options.tessellation || 64 | 0;
  62854. var radiusFunction = options.radiusFunction || null;
  62855. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62856. var invertUV = options.invertUV || false;
  62857. var updatable = options.updatable;
  62858. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62859. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  62860. // tube geometry
  62861. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  62862. var tangents = path3D.getTangents();
  62863. var normals = path3D.getNormals();
  62864. var distances = path3D.getDistances();
  62865. var pi2 = Math.PI * 2;
  62866. var step = pi2 / tessellation * arc;
  62867. var returnRadius = function () { return radius; };
  62868. var radiusFunctionFinal = radiusFunction || returnRadius;
  62869. var circlePath;
  62870. var rad;
  62871. var normal;
  62872. var rotated;
  62873. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62874. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62875. for (var i = 0; i < path.length; i++) {
  62876. rad = radiusFunctionFinal(i, distances[i]); // current radius
  62877. circlePath = Array(); // current circle array
  62878. normal = normals[i]; // current normal
  62879. for (var t = 0; t < tessellation; t++) {
  62880. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  62881. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  62882. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  62883. rotated.scaleInPlace(rad).addInPlace(path[i]);
  62884. circlePath[t] = rotated;
  62885. }
  62886. circlePaths[index] = circlePath;
  62887. index++;
  62888. }
  62889. // cap
  62890. var capPath = function (nbPoints, pathIndex) {
  62891. var pointCap = Array();
  62892. for (var i = 0; i < nbPoints; i++) {
  62893. pointCap.push(path[pathIndex]);
  62894. }
  62895. return pointCap;
  62896. };
  62897. switch (cap) {
  62898. case BABYLON.Mesh.NO_CAP:
  62899. break;
  62900. case BABYLON.Mesh.CAP_START:
  62901. circlePaths[0] = capPath(tessellation, 0);
  62902. circlePaths[1] = circlePaths[2].slice(0);
  62903. break;
  62904. case BABYLON.Mesh.CAP_END:
  62905. circlePaths[index] = circlePaths[index - 1].slice(0);
  62906. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62907. break;
  62908. case BABYLON.Mesh.CAP_ALL:
  62909. circlePaths[0] = capPath(tessellation, 0);
  62910. circlePaths[1] = circlePaths[2].slice(0);
  62911. circlePaths[index] = circlePaths[index - 1].slice(0);
  62912. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62913. break;
  62914. default:
  62915. break;
  62916. }
  62917. return circlePaths;
  62918. };
  62919. var path3D;
  62920. var pathArray;
  62921. if (instance) { // tube update
  62922. var arc = options.arc || instance.arc;
  62923. path3D = (instance.path3D).update(path);
  62924. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  62925. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  62926. instance.path3D = path3D;
  62927. instance.pathArray = pathArray;
  62928. instance.arc = arc;
  62929. instance.radius = radius;
  62930. return instance;
  62931. }
  62932. // tube creation
  62933. path3D = new BABYLON.Path3D(path);
  62934. var newPathArray = new Array();
  62935. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62936. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  62937. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62938. tube.pathArray = pathArray;
  62939. tube.path3D = path3D;
  62940. tube.tessellation = tessellation;
  62941. tube.cap = cap;
  62942. tube.arc = options.arc;
  62943. tube.radius = radius;
  62944. return tube;
  62945. };
  62946. /**
  62947. * Creates a polyhedron mesh
  62948. * * 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
  62949. * * The parameter `size` (positive float, default 1) sets the polygon size
  62950. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  62951. * * 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`
  62952. * * 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
  62953. * * 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)`)
  62954. * * 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
  62955. * * 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
  62956. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62957. * * 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
  62958. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62959. * @param name defines the name of the mesh
  62960. * @param options defines the options used to create the mesh
  62961. * @param scene defines the hosting scene
  62962. * @returns the polyhedron mesh
  62963. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  62964. */
  62965. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  62966. var polyhedron = new BABYLON.Mesh(name, scene);
  62967. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62968. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  62969. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  62970. vertexData.applyToMesh(polyhedron, options.updatable);
  62971. return polyhedron;
  62972. };
  62973. /**
  62974. * Creates a decal mesh.
  62975. * 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
  62976. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  62977. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  62978. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  62979. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  62980. * @param name defines the name of the mesh
  62981. * @param sourceMesh defines the mesh where the decal must be applied
  62982. * @param options defines the options used to create the mesh
  62983. * @param scene defines the hosting scene
  62984. * @returns the decal mesh
  62985. * @see http://doc.babylonjs.com/how_to/decals
  62986. */
  62987. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  62988. var indices = sourceMesh.getIndices();
  62989. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62990. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62991. var position = options.position || BABYLON.Vector3.Zero();
  62992. var normal = options.normal || BABYLON.Vector3.Up();
  62993. var size = options.size || BABYLON.Vector3.One();
  62994. var angle = options.angle || 0;
  62995. // Getting correct rotation
  62996. if (!normal) {
  62997. var target = new BABYLON.Vector3(0, 0, 1);
  62998. var camera = sourceMesh.getScene().activeCamera;
  62999. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  63000. normal = camera.globalPosition.subtract(cameraWorldTarget);
  63001. }
  63002. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  63003. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  63004. var pitch = Math.atan2(normal.y, len);
  63005. // Matrix
  63006. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  63007. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  63008. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  63009. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  63010. var vertexData = new BABYLON.VertexData();
  63011. vertexData.indices = [];
  63012. vertexData.positions = [];
  63013. vertexData.normals = [];
  63014. vertexData.uvs = [];
  63015. var currentVertexDataIndex = 0;
  63016. var extractDecalVector3 = function (indexId) {
  63017. var result = new BABYLON.PositionNormalVertex();
  63018. if (!indices || !positions || !normals) {
  63019. return result;
  63020. }
  63021. var vertexId = indices[indexId];
  63022. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  63023. // Send vector to decal local world
  63024. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  63025. // Get normal
  63026. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  63027. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  63028. return result;
  63029. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  63030. var clip = function (vertices, axis) {
  63031. if (vertices.length === 0) {
  63032. return vertices;
  63033. }
  63034. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  63035. var clipVertices = function (v0, v1) {
  63036. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  63037. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  63038. };
  63039. var result = new Array();
  63040. for (var index = 0; index < vertices.length; index += 3) {
  63041. var v1Out;
  63042. var v2Out;
  63043. var v3Out;
  63044. var total = 0;
  63045. var nV1 = null;
  63046. var nV2 = null;
  63047. var nV3 = null;
  63048. var nV4 = null;
  63049. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  63050. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  63051. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  63052. v1Out = d1 > 0;
  63053. v2Out = d2 > 0;
  63054. v3Out = d3 > 0;
  63055. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  63056. switch (total) {
  63057. case 0:
  63058. result.push(vertices[index]);
  63059. result.push(vertices[index + 1]);
  63060. result.push(vertices[index + 2]);
  63061. break;
  63062. case 1:
  63063. if (v1Out) {
  63064. nV1 = vertices[index + 1];
  63065. nV2 = vertices[index + 2];
  63066. nV3 = clipVertices(vertices[index], nV1);
  63067. nV4 = clipVertices(vertices[index], nV2);
  63068. }
  63069. if (v2Out) {
  63070. nV1 = vertices[index];
  63071. nV2 = vertices[index + 2];
  63072. nV3 = clipVertices(vertices[index + 1], nV1);
  63073. nV4 = clipVertices(vertices[index + 1], nV2);
  63074. result.push(nV3);
  63075. result.push(nV2.clone());
  63076. result.push(nV1.clone());
  63077. result.push(nV2.clone());
  63078. result.push(nV3.clone());
  63079. result.push(nV4);
  63080. break;
  63081. }
  63082. if (v3Out) {
  63083. nV1 = vertices[index];
  63084. nV2 = vertices[index + 1];
  63085. nV3 = clipVertices(vertices[index + 2], nV1);
  63086. nV4 = clipVertices(vertices[index + 2], nV2);
  63087. }
  63088. if (nV1 && nV2 && nV3 && nV4) {
  63089. result.push(nV1.clone());
  63090. result.push(nV2.clone());
  63091. result.push(nV3);
  63092. result.push(nV4);
  63093. result.push(nV3.clone());
  63094. result.push(nV2.clone());
  63095. }
  63096. break;
  63097. case 2:
  63098. if (!v1Out) {
  63099. nV1 = vertices[index].clone();
  63100. nV2 = clipVertices(nV1, vertices[index + 1]);
  63101. nV3 = clipVertices(nV1, vertices[index + 2]);
  63102. result.push(nV1);
  63103. result.push(nV2);
  63104. result.push(nV3);
  63105. }
  63106. if (!v2Out) {
  63107. nV1 = vertices[index + 1].clone();
  63108. nV2 = clipVertices(nV1, vertices[index + 2]);
  63109. nV3 = clipVertices(nV1, vertices[index]);
  63110. result.push(nV1);
  63111. result.push(nV2);
  63112. result.push(nV3);
  63113. }
  63114. if (!v3Out) {
  63115. nV1 = vertices[index + 2].clone();
  63116. nV2 = clipVertices(nV1, vertices[index]);
  63117. nV3 = clipVertices(nV1, vertices[index + 1]);
  63118. result.push(nV1);
  63119. result.push(nV2);
  63120. result.push(nV3);
  63121. }
  63122. break;
  63123. case 3:
  63124. break;
  63125. }
  63126. }
  63127. return result;
  63128. };
  63129. for (var index = 0; index < indices.length; index += 3) {
  63130. var faceVertices = new Array();
  63131. faceVertices.push(extractDecalVector3(index));
  63132. faceVertices.push(extractDecalVector3(index + 1));
  63133. faceVertices.push(extractDecalVector3(index + 2));
  63134. // Clip
  63135. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  63136. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  63137. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  63138. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  63139. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  63140. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  63141. if (faceVertices.length === 0) {
  63142. continue;
  63143. }
  63144. // Add UVs and get back to world
  63145. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  63146. var vertex = faceVertices[vIndex];
  63147. //TODO check for Int32Array | Uint32Array | Uint16Array
  63148. vertexData.indices.push(currentVertexDataIndex);
  63149. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  63150. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  63151. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  63152. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  63153. currentVertexDataIndex++;
  63154. }
  63155. }
  63156. // Return mesh
  63157. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  63158. vertexData.applyToMesh(decal);
  63159. decal.position = position.clone();
  63160. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  63161. return decal;
  63162. };
  63163. // Privates
  63164. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  63165. // extrusion geometry
  63166. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  63167. var tangents = path3D.getTangents();
  63168. var normals = path3D.getNormals();
  63169. var binormals = path3D.getBinormals();
  63170. var distances = path3D.getDistances();
  63171. var angle = 0;
  63172. var returnScale = function () { return scale !== null ? scale : 1; };
  63173. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  63174. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  63175. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  63176. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63177. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63178. for (var i = 0; i < curve.length; i++) {
  63179. var shapePath = new Array();
  63180. var angleStep = rotate(i, distances[i]);
  63181. var scaleRatio = scl(i, distances[i]);
  63182. for (var p = 0; p < shape.length; p++) {
  63183. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  63184. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  63185. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  63186. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  63187. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  63188. shapePath[p] = rotated;
  63189. }
  63190. shapePaths[index] = shapePath;
  63191. angle += angleStep;
  63192. index++;
  63193. }
  63194. // cap
  63195. var capPath = function (shapePath) {
  63196. var pointCap = Array();
  63197. var barycenter = BABYLON.Vector3.Zero();
  63198. var i;
  63199. for (i = 0; i < shapePath.length; i++) {
  63200. barycenter.addInPlace(shapePath[i]);
  63201. }
  63202. barycenter.scaleInPlace(1.0 / shapePath.length);
  63203. for (i = 0; i < shapePath.length; i++) {
  63204. pointCap.push(barycenter);
  63205. }
  63206. return pointCap;
  63207. };
  63208. switch (cap) {
  63209. case BABYLON.Mesh.NO_CAP:
  63210. break;
  63211. case BABYLON.Mesh.CAP_START:
  63212. shapePaths[0] = capPath(shapePaths[2]);
  63213. shapePaths[1] = shapePaths[2];
  63214. break;
  63215. case BABYLON.Mesh.CAP_END:
  63216. shapePaths[index] = shapePaths[index - 1];
  63217. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63218. break;
  63219. case BABYLON.Mesh.CAP_ALL:
  63220. shapePaths[0] = capPath(shapePaths[2]);
  63221. shapePaths[1] = shapePaths[2];
  63222. shapePaths[index] = shapePaths[index - 1];
  63223. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63224. break;
  63225. default:
  63226. break;
  63227. }
  63228. return shapePaths;
  63229. };
  63230. var path3D;
  63231. var pathArray;
  63232. if (instance) { // instance update
  63233. path3D = (instance.path3D).update(curve);
  63234. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  63235. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  63236. return instance;
  63237. }
  63238. // extruded shape creation
  63239. path3D = new BABYLON.Path3D(curve);
  63240. var newShapePaths = new Array();
  63241. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63242. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  63243. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  63244. extrudedGeneric.pathArray = pathArray;
  63245. extrudedGeneric.path3D = path3D;
  63246. extrudedGeneric.cap = cap;
  63247. return extrudedGeneric;
  63248. };
  63249. return MeshBuilder;
  63250. }());
  63251. BABYLON.MeshBuilder = MeshBuilder;
  63252. })(BABYLON || (BABYLON = {}));
  63253. //# sourceMappingURL=babylon.meshBuilder.js.map
  63254. var BABYLON;
  63255. (function (BABYLON) {
  63256. /**
  63257. * Draco compression (https://google.github.io/draco/)
  63258. *
  63259. * This class wraps the Draco module.
  63260. *
  63261. * **Encoder**
  63262. *
  63263. * The encoder is not currently implemented.
  63264. *
  63265. * **Decoder**
  63266. *
  63267. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  63268. *
  63269. * To update the configuration, use the following code:
  63270. * ```javascript
  63271. * BABYLON.DracoCompression.Configuration = {
  63272. * decoder: {
  63273. * wasmUrl: "<url to the WebAssembly library>",
  63274. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  63275. * fallbackUrl: "<url to the fallback JavaScript library>",
  63276. * }
  63277. * };
  63278. * ```
  63279. *
  63280. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  63281. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  63282. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  63283. *
  63284. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  63285. * ```javascript
  63286. * var dracoCompression = new BABYLON.DracoCompression();
  63287. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  63288. * [BABYLON.VertexBuffer.PositionKind]: 0
  63289. * });
  63290. * ```
  63291. *
  63292. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  63293. */
  63294. var DracoCompression = /** @class */ (function () {
  63295. /**
  63296. * Constructor
  63297. */
  63298. function DracoCompression() {
  63299. }
  63300. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  63301. /**
  63302. * Returns true if the decoder is available.
  63303. */
  63304. get: function () {
  63305. if (typeof DracoDecoderModule !== "undefined") {
  63306. return true;
  63307. }
  63308. var decoder = DracoCompression.Configuration.decoder;
  63309. if (decoder) {
  63310. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63311. return true;
  63312. }
  63313. if (decoder.fallbackUrl) {
  63314. return true;
  63315. }
  63316. }
  63317. return false;
  63318. },
  63319. enumerable: true,
  63320. configurable: true
  63321. });
  63322. /**
  63323. * Stop all async operations and release resources.
  63324. */
  63325. DracoCompression.prototype.dispose = function () {
  63326. };
  63327. /**
  63328. * Decode Draco compressed mesh data to vertex data.
  63329. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  63330. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  63331. * @returns A promise that resolves with the decoded vertex data
  63332. */
  63333. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  63334. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  63335. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  63336. var module = wrappedModule.module;
  63337. var vertexData = new BABYLON.VertexData();
  63338. var buffer = new module.DecoderBuffer();
  63339. buffer.Init(dataView, dataView.byteLength);
  63340. var decoder = new module.Decoder();
  63341. var geometry;
  63342. var status;
  63343. try {
  63344. var type = decoder.GetEncodedGeometryType(buffer);
  63345. switch (type) {
  63346. case module.TRIANGULAR_MESH:
  63347. geometry = new module.Mesh();
  63348. status = decoder.DecodeBufferToMesh(buffer, geometry);
  63349. break;
  63350. case module.POINT_CLOUD:
  63351. geometry = new module.PointCloud();
  63352. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  63353. break;
  63354. default:
  63355. throw new Error("Invalid geometry type " + type);
  63356. }
  63357. if (!status.ok() || !geometry.ptr) {
  63358. throw new Error(status.error_msg());
  63359. }
  63360. var numPoints = geometry.num_points();
  63361. if (type === module.TRIANGULAR_MESH) {
  63362. var numFaces = geometry.num_faces();
  63363. var faceIndices = new module.DracoInt32Array();
  63364. try {
  63365. var indices = new Uint32Array(numFaces * 3);
  63366. for (var i = 0; i < numFaces; i++) {
  63367. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  63368. var offset = i * 3;
  63369. indices[offset + 0] = faceIndices.GetValue(0);
  63370. indices[offset + 1] = faceIndices.GetValue(1);
  63371. indices[offset + 2] = faceIndices.GetValue(2);
  63372. }
  63373. vertexData.indices = indices;
  63374. }
  63375. finally {
  63376. module.destroy(faceIndices);
  63377. }
  63378. }
  63379. for (var kind in attributes) {
  63380. var uniqueId = attributes[kind];
  63381. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  63382. var dracoData = new module.DracoFloat32Array();
  63383. try {
  63384. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  63385. var babylonData = new Float32Array(numPoints * attribute.num_components());
  63386. for (var i = 0; i < babylonData.length; i++) {
  63387. babylonData[i] = dracoData.GetValue(i);
  63388. }
  63389. vertexData.set(babylonData, kind);
  63390. }
  63391. finally {
  63392. module.destroy(dracoData);
  63393. }
  63394. }
  63395. }
  63396. finally {
  63397. if (geometry) {
  63398. module.destroy(geometry);
  63399. }
  63400. module.destroy(decoder);
  63401. module.destroy(buffer);
  63402. }
  63403. return vertexData;
  63404. });
  63405. };
  63406. DracoCompression._GetDecoderModule = function () {
  63407. if (!DracoCompression._DecoderModulePromise) {
  63408. var promise = null;
  63409. var config_1 = {};
  63410. if (typeof DracoDecoderModule !== "undefined") {
  63411. promise = Promise.resolve();
  63412. }
  63413. else {
  63414. var decoder = DracoCompression.Configuration.decoder;
  63415. if (decoder) {
  63416. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63417. promise = Promise.all([
  63418. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  63419. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  63420. config_1.wasmBinary = data;
  63421. })
  63422. ]);
  63423. }
  63424. else if (decoder.fallbackUrl) {
  63425. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  63426. }
  63427. }
  63428. }
  63429. if (!promise) {
  63430. throw new Error("Draco decoder module is not available");
  63431. }
  63432. DracoCompression._DecoderModulePromise = promise.then(function () {
  63433. return new Promise(function (resolve) {
  63434. config_1.onModuleLoaded = function (decoderModule) {
  63435. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  63436. resolve({ module: decoderModule });
  63437. };
  63438. DracoDecoderModule(config_1);
  63439. });
  63440. });
  63441. }
  63442. return DracoCompression._DecoderModulePromise;
  63443. };
  63444. DracoCompression._LoadScriptAsync = function (url) {
  63445. return new Promise(function (resolve, reject) {
  63446. BABYLON.Tools.LoadScript(url, function () {
  63447. resolve();
  63448. }, function (message) {
  63449. reject(new Error(message));
  63450. });
  63451. });
  63452. };
  63453. DracoCompression._LoadFileAsync = function (url) {
  63454. return new Promise(function (resolve, reject) {
  63455. BABYLON.Tools.LoadFile(url, function (data) {
  63456. resolve(data);
  63457. }, undefined, undefined, true, function (request, exception) {
  63458. reject(exception);
  63459. });
  63460. });
  63461. };
  63462. /**
  63463. * The configuration. Defaults to the following urls:
  63464. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  63465. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  63466. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63467. */
  63468. DracoCompression.Configuration = {
  63469. decoder: {
  63470. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  63471. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  63472. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63473. }
  63474. };
  63475. return DracoCompression;
  63476. }());
  63477. BABYLON.DracoCompression = DracoCompression;
  63478. })(BABYLON || (BABYLON = {}));
  63479. //# sourceMappingURL=babylon.dracoCompression.js.map
  63480. var BABYLON;
  63481. (function (BABYLON) {
  63482. var AudioEngine = /** @class */ (function () {
  63483. function AudioEngine() {
  63484. this._audioContext = null;
  63485. this._audioContextInitialized = false;
  63486. this.canUseWebAudio = false;
  63487. this.WarnedWebAudioUnsupported = false;
  63488. this.unlocked = false;
  63489. this.isMP3supported = false;
  63490. this.isOGGsupported = false;
  63491. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  63492. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  63493. this.canUseWebAudio = true;
  63494. }
  63495. var audioElem = document.createElement('audio');
  63496. try {
  63497. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  63498. this.isMP3supported = true;
  63499. }
  63500. }
  63501. catch (e) {
  63502. // protect error during capability check.
  63503. }
  63504. try {
  63505. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  63506. this.isOGGsupported = true;
  63507. }
  63508. }
  63509. catch (e) {
  63510. // protect error during capability check.
  63511. }
  63512. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  63513. this._unlockiOSaudio();
  63514. }
  63515. else {
  63516. this.unlocked = true;
  63517. }
  63518. }
  63519. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  63520. get: function () {
  63521. if (!this._audioContextInitialized) {
  63522. this._initializeAudioContext();
  63523. }
  63524. return this._audioContext;
  63525. },
  63526. enumerable: true,
  63527. configurable: true
  63528. });
  63529. AudioEngine.prototype._unlockiOSaudio = function () {
  63530. var _this = this;
  63531. var unlockaudio = function () {
  63532. if (!_this.audioContext) {
  63533. return;
  63534. }
  63535. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  63536. var source = _this.audioContext.createBufferSource();
  63537. source.buffer = buffer;
  63538. source.connect(_this.audioContext.destination);
  63539. source.start(0);
  63540. setTimeout(function () {
  63541. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  63542. _this.unlocked = true;
  63543. window.removeEventListener('touchend', unlockaudio, false);
  63544. if (_this.onAudioUnlocked) {
  63545. _this.onAudioUnlocked();
  63546. }
  63547. }
  63548. }, 0);
  63549. };
  63550. window.addEventListener('touchend', unlockaudio, false);
  63551. };
  63552. AudioEngine.prototype._initializeAudioContext = function () {
  63553. try {
  63554. if (this.canUseWebAudio) {
  63555. this._audioContext = new AudioContext();
  63556. // create a global volume gain node
  63557. this.masterGain = this._audioContext.createGain();
  63558. this.masterGain.gain.value = 1;
  63559. this.masterGain.connect(this._audioContext.destination);
  63560. this._audioContextInitialized = true;
  63561. }
  63562. }
  63563. catch (e) {
  63564. this.canUseWebAudio = false;
  63565. BABYLON.Tools.Error("Web Audio: " + e.message);
  63566. }
  63567. };
  63568. AudioEngine.prototype.dispose = function () {
  63569. if (this.canUseWebAudio && this._audioContextInitialized) {
  63570. if (this._connectedAnalyser && this._audioContext) {
  63571. this._connectedAnalyser.stopDebugCanvas();
  63572. this._connectedAnalyser.dispose();
  63573. this.masterGain.disconnect();
  63574. this.masterGain.connect(this._audioContext.destination);
  63575. this._connectedAnalyser = null;
  63576. }
  63577. this.masterGain.gain.value = 1;
  63578. }
  63579. this.WarnedWebAudioUnsupported = false;
  63580. };
  63581. AudioEngine.prototype.getGlobalVolume = function () {
  63582. if (this.canUseWebAudio && this._audioContextInitialized) {
  63583. return this.masterGain.gain.value;
  63584. }
  63585. else {
  63586. return -1;
  63587. }
  63588. };
  63589. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  63590. if (this.canUseWebAudio && this._audioContextInitialized) {
  63591. this.masterGain.gain.value = newVolume;
  63592. }
  63593. };
  63594. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  63595. if (this._connectedAnalyser) {
  63596. this._connectedAnalyser.stopDebugCanvas();
  63597. }
  63598. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  63599. this._connectedAnalyser = analyser;
  63600. this.masterGain.disconnect();
  63601. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  63602. }
  63603. };
  63604. return AudioEngine;
  63605. }());
  63606. BABYLON.AudioEngine = AudioEngine;
  63607. })(BABYLON || (BABYLON = {}));
  63608. //# sourceMappingURL=babylon.audioEngine.js.map
  63609. var BABYLON;
  63610. (function (BABYLON) {
  63611. var Sound = /** @class */ (function () {
  63612. /**
  63613. * Create a sound and attach it to a scene
  63614. * @param name Name of your sound
  63615. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  63616. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  63617. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  63618. */
  63619. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  63620. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  63621. var _this = this;
  63622. this.autoplay = false;
  63623. this.loop = false;
  63624. this.useCustomAttenuation = false;
  63625. this.spatialSound = false;
  63626. this.refDistance = 1;
  63627. this.rolloffFactor = 1;
  63628. this.maxDistance = 100;
  63629. this.distanceModel = "linear";
  63630. this._panningModel = "equalpower";
  63631. this._playbackRate = 1;
  63632. this._streaming = false;
  63633. this._startTime = 0;
  63634. this._startOffset = 0;
  63635. this._position = BABYLON.Vector3.Zero();
  63636. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  63637. this._volume = 1;
  63638. this._isReadyToPlay = false;
  63639. this.isPlaying = false;
  63640. this.isPaused = false;
  63641. this._isDirectional = false;
  63642. // Used if you'd like to create a directional sound.
  63643. // If not set, the sound will be omnidirectional
  63644. this._coneInnerAngle = 360;
  63645. this._coneOuterAngle = 360;
  63646. this._coneOuterGain = 0;
  63647. this._isOutputConnected = false;
  63648. this._urlType = "Unknown";
  63649. this.name = name;
  63650. this._scene = scene;
  63651. this._readyToPlayCallback = readyToPlayCallback;
  63652. // Default custom attenuation function is a linear attenuation
  63653. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  63654. if (currentDistance < maxDistance) {
  63655. return currentVolume * (1 - currentDistance / maxDistance);
  63656. }
  63657. else {
  63658. return 0;
  63659. }
  63660. };
  63661. if (options) {
  63662. this.autoplay = options.autoplay || false;
  63663. this.loop = options.loop || false;
  63664. // if volume === 0, we need another way to check this option
  63665. if (options.volume !== undefined) {
  63666. this._volume = options.volume;
  63667. }
  63668. this.spatialSound = options.spatialSound || false;
  63669. this.maxDistance = options.maxDistance || 100;
  63670. this.useCustomAttenuation = options.useCustomAttenuation || false;
  63671. this.rolloffFactor = options.rolloffFactor || 1;
  63672. this.refDistance = options.refDistance || 1;
  63673. this.distanceModel = options.distanceModel || "linear";
  63674. this._playbackRate = options.playbackRate || 1;
  63675. this._streaming = options.streaming || false;
  63676. }
  63677. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63678. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  63679. this._soundGain.gain.value = this._volume;
  63680. this._inputAudioNode = this._soundGain;
  63681. this._ouputAudioNode = this._soundGain;
  63682. if (this.spatialSound) {
  63683. this._createSpatialParameters();
  63684. }
  63685. this._scene.mainSoundTrack.AddSound(this);
  63686. var validParameter = true;
  63687. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  63688. if (urlOrArrayBuffer) {
  63689. try {
  63690. if (typeof (urlOrArrayBuffer) === "string") {
  63691. this._urlType = "String";
  63692. }
  63693. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  63694. this._urlType = "ArrayBuffer";
  63695. }
  63696. else if (urlOrArrayBuffer instanceof MediaStream) {
  63697. this._urlType = "MediaStream";
  63698. }
  63699. else if (Array.isArray(urlOrArrayBuffer)) {
  63700. this._urlType = "Array";
  63701. }
  63702. var urls = [];
  63703. var codecSupportedFound = false;
  63704. switch (this._urlType) {
  63705. case "MediaStream":
  63706. this._streaming = true;
  63707. this._isReadyToPlay = true;
  63708. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  63709. if (this.autoplay) {
  63710. this.play();
  63711. }
  63712. if (this._readyToPlayCallback) {
  63713. this._readyToPlayCallback();
  63714. }
  63715. break;
  63716. case "ArrayBuffer":
  63717. if (urlOrArrayBuffer.byteLength > 0) {
  63718. codecSupportedFound = true;
  63719. this._soundLoaded(urlOrArrayBuffer);
  63720. }
  63721. break;
  63722. case "String":
  63723. urls.push(urlOrArrayBuffer);
  63724. case "Array":
  63725. if (urls.length === 0)
  63726. urls = urlOrArrayBuffer;
  63727. // If we found a supported format, we load it immediately and stop the loop
  63728. for (var i = 0; i < urls.length; i++) {
  63729. var url = urls[i];
  63730. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  63731. codecSupportedFound = true;
  63732. }
  63733. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  63734. codecSupportedFound = true;
  63735. }
  63736. if (url.indexOf(".wav", url.length - 4) !== -1) {
  63737. codecSupportedFound = true;
  63738. }
  63739. if (url.indexOf("blob:") !== -1) {
  63740. codecSupportedFound = true;
  63741. }
  63742. if (codecSupportedFound) {
  63743. // Loading sound using XHR2
  63744. if (!this._streaming) {
  63745. this._scene._loadFile(url, function (data) {
  63746. _this._soundLoaded(data);
  63747. }, undefined, true, true, function (exception) {
  63748. if (exception) {
  63749. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  63750. }
  63751. BABYLON.Tools.Error("Sound creation aborted.");
  63752. _this._scene.mainSoundTrack.RemoveSound(_this);
  63753. });
  63754. }
  63755. // Streaming sound using HTML5 Audio tag
  63756. else {
  63757. this._htmlAudioElement = new Audio(url);
  63758. this._htmlAudioElement.controls = false;
  63759. this._htmlAudioElement.loop = this.loop;
  63760. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  63761. this._htmlAudioElement.preload = "auto";
  63762. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  63763. _this._isReadyToPlay = true;
  63764. if (_this.autoplay) {
  63765. _this.play();
  63766. }
  63767. if (_this._readyToPlayCallback) {
  63768. _this._readyToPlayCallback();
  63769. }
  63770. });
  63771. document.body.appendChild(this._htmlAudioElement);
  63772. }
  63773. break;
  63774. }
  63775. }
  63776. break;
  63777. default:
  63778. validParameter = false;
  63779. break;
  63780. }
  63781. if (!validParameter) {
  63782. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  63783. }
  63784. else {
  63785. if (!codecSupportedFound) {
  63786. this._isReadyToPlay = true;
  63787. // Simulating a ready to play event to avoid breaking code path
  63788. if (this._readyToPlayCallback) {
  63789. window.setTimeout(function () {
  63790. if (_this._readyToPlayCallback) {
  63791. _this._readyToPlayCallback();
  63792. }
  63793. }, 1000);
  63794. }
  63795. }
  63796. }
  63797. }
  63798. catch (ex) {
  63799. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  63800. this._scene.mainSoundTrack.RemoveSound(this);
  63801. }
  63802. }
  63803. }
  63804. else {
  63805. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  63806. this._scene.mainSoundTrack.AddSound(this);
  63807. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  63808. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  63809. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  63810. }
  63811. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  63812. if (this._readyToPlayCallback) {
  63813. window.setTimeout(function () {
  63814. if (_this._readyToPlayCallback) {
  63815. _this._readyToPlayCallback();
  63816. }
  63817. }, 1000);
  63818. }
  63819. }
  63820. }
  63821. Sound.prototype.dispose = function () {
  63822. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63823. if (this.isPlaying) {
  63824. this.stop();
  63825. }
  63826. this._isReadyToPlay = false;
  63827. if (this.soundTrackId === -1) {
  63828. this._scene.mainSoundTrack.RemoveSound(this);
  63829. }
  63830. else {
  63831. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  63832. }
  63833. if (this._soundGain) {
  63834. this._soundGain.disconnect();
  63835. this._soundGain = null;
  63836. }
  63837. if (this._soundPanner) {
  63838. this._soundPanner.disconnect();
  63839. this._soundPanner = null;
  63840. }
  63841. if (this._soundSource) {
  63842. this._soundSource.disconnect();
  63843. this._soundSource = null;
  63844. }
  63845. this._audioBuffer = null;
  63846. if (this._htmlAudioElement) {
  63847. this._htmlAudioElement.pause();
  63848. this._htmlAudioElement.src = "";
  63849. document.body.removeChild(this._htmlAudioElement);
  63850. }
  63851. if (this._streamingSource) {
  63852. this._streamingSource.disconnect();
  63853. }
  63854. if (this._connectedMesh && this._registerFunc) {
  63855. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63856. this._connectedMesh = null;
  63857. }
  63858. }
  63859. };
  63860. Sound.prototype.isReady = function () {
  63861. return this._isReadyToPlay;
  63862. };
  63863. Sound.prototype._soundLoaded = function (audioData) {
  63864. var _this = this;
  63865. if (!BABYLON.Engine.audioEngine.audioContext) {
  63866. return;
  63867. }
  63868. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  63869. _this._audioBuffer = buffer;
  63870. _this._isReadyToPlay = true;
  63871. if (_this.autoplay) {
  63872. _this.play();
  63873. }
  63874. if (_this._readyToPlayCallback) {
  63875. _this._readyToPlayCallback();
  63876. }
  63877. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  63878. };
  63879. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  63880. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63881. this._audioBuffer = audioBuffer;
  63882. this._isReadyToPlay = true;
  63883. }
  63884. };
  63885. Sound.prototype.updateOptions = function (options) {
  63886. if (options) {
  63887. this.loop = options.loop || this.loop;
  63888. this.maxDistance = options.maxDistance || this.maxDistance;
  63889. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  63890. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  63891. this.refDistance = options.refDistance || this.refDistance;
  63892. this.distanceModel = options.distanceModel || this.distanceModel;
  63893. this._playbackRate = options.playbackRate || this._playbackRate;
  63894. this._updateSpatialParameters();
  63895. if (this.isPlaying) {
  63896. if (this._streaming && this._htmlAudioElement) {
  63897. this._htmlAudioElement.playbackRate = this._playbackRate;
  63898. }
  63899. else {
  63900. if (this._soundSource) {
  63901. this._soundSource.playbackRate.value = this._playbackRate;
  63902. }
  63903. }
  63904. }
  63905. }
  63906. };
  63907. Sound.prototype._createSpatialParameters = function () {
  63908. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63909. if (this._scene.headphone) {
  63910. this._panningModel = "HRTF";
  63911. }
  63912. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  63913. this._updateSpatialParameters();
  63914. this._soundPanner.connect(this._ouputAudioNode);
  63915. this._inputAudioNode = this._soundPanner;
  63916. }
  63917. };
  63918. Sound.prototype._updateSpatialParameters = function () {
  63919. if (this.spatialSound && this._soundPanner) {
  63920. if (this.useCustomAttenuation) {
  63921. // Tricks to disable in a way embedded Web Audio attenuation
  63922. this._soundPanner.distanceModel = "linear";
  63923. this._soundPanner.maxDistance = Number.MAX_VALUE;
  63924. this._soundPanner.refDistance = 1;
  63925. this._soundPanner.rolloffFactor = 1;
  63926. this._soundPanner.panningModel = this._panningModel;
  63927. }
  63928. else {
  63929. this._soundPanner.distanceModel = this.distanceModel;
  63930. this._soundPanner.maxDistance = this.maxDistance;
  63931. this._soundPanner.refDistance = this.refDistance;
  63932. this._soundPanner.rolloffFactor = this.rolloffFactor;
  63933. this._soundPanner.panningModel = this._panningModel;
  63934. }
  63935. }
  63936. };
  63937. Sound.prototype.switchPanningModelToHRTF = function () {
  63938. this._panningModel = "HRTF";
  63939. this._switchPanningModel();
  63940. };
  63941. Sound.prototype.switchPanningModelToEqualPower = function () {
  63942. this._panningModel = "equalpower";
  63943. this._switchPanningModel();
  63944. };
  63945. Sound.prototype._switchPanningModel = function () {
  63946. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63947. this._soundPanner.panningModel = this._panningModel;
  63948. }
  63949. };
  63950. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  63951. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63952. if (this._isOutputConnected) {
  63953. this._ouputAudioNode.disconnect();
  63954. }
  63955. this._ouputAudioNode.connect(soundTrackAudioNode);
  63956. this._isOutputConnected = true;
  63957. }
  63958. };
  63959. /**
  63960. * Transform this sound into a directional source
  63961. * @param coneInnerAngle Size of the inner cone in degree
  63962. * @param coneOuterAngle Size of the outer cone in degree
  63963. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  63964. */
  63965. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  63966. if (coneOuterAngle < coneInnerAngle) {
  63967. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  63968. return;
  63969. }
  63970. this._coneInnerAngle = coneInnerAngle;
  63971. this._coneOuterAngle = coneOuterAngle;
  63972. this._coneOuterGain = coneOuterGain;
  63973. this._isDirectional = true;
  63974. if (this.isPlaying && this.loop) {
  63975. this.stop();
  63976. this.play();
  63977. }
  63978. };
  63979. Sound.prototype.setPosition = function (newPosition) {
  63980. this._position = newPosition;
  63981. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63982. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63983. }
  63984. };
  63985. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  63986. this._localDirection = newLocalDirection;
  63987. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  63988. this._updateDirection();
  63989. }
  63990. };
  63991. Sound.prototype._updateDirection = function () {
  63992. if (!this._connectedMesh || !this._soundPanner) {
  63993. return;
  63994. }
  63995. var mat = this._connectedMesh.getWorldMatrix();
  63996. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  63997. direction.normalize();
  63998. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  63999. };
  64000. Sound.prototype.updateDistanceFromListener = function () {
  64001. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  64002. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  64003. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  64004. }
  64005. };
  64006. Sound.prototype.setAttenuationFunction = function (callback) {
  64007. this._customAttenuationFunction = callback;
  64008. };
  64009. /**
  64010. * Play the sound
  64011. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  64012. * @param offset (optional) Start the sound setting it at a specific time
  64013. */
  64014. Sound.prototype.play = function (time, offset) {
  64015. var _this = this;
  64016. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  64017. try {
  64018. if (this._startOffset < 0) {
  64019. time = -this._startOffset;
  64020. this._startOffset = 0;
  64021. }
  64022. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64023. if (!this._soundSource || !this._streamingSource) {
  64024. if (this.spatialSound && this._soundPanner) {
  64025. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64026. if (this._isDirectional) {
  64027. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64028. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  64029. this._soundPanner.coneOuterGain = this._coneOuterGain;
  64030. if (this._connectedMesh) {
  64031. this._updateDirection();
  64032. }
  64033. else {
  64034. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  64035. }
  64036. }
  64037. }
  64038. }
  64039. if (this._streaming) {
  64040. if (!this._streamingSource) {
  64041. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  64042. this._htmlAudioElement.onended = function () { _this._onended(); };
  64043. this._htmlAudioElement.playbackRate = this._playbackRate;
  64044. }
  64045. this._streamingSource.disconnect();
  64046. this._streamingSource.connect(this._inputAudioNode);
  64047. if (this._htmlAudioElement) {
  64048. this._htmlAudioElement.play();
  64049. }
  64050. }
  64051. else {
  64052. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  64053. this._soundSource.buffer = this._audioBuffer;
  64054. this._soundSource.connect(this._inputAudioNode);
  64055. this._soundSource.loop = this.loop;
  64056. this._soundSource.playbackRate.value = this._playbackRate;
  64057. this._soundSource.onended = function () { _this._onended(); };
  64058. if (this._soundSource.buffer) {
  64059. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  64060. }
  64061. }
  64062. this._startTime = startTime;
  64063. this.isPlaying = true;
  64064. this.isPaused = false;
  64065. }
  64066. catch (ex) {
  64067. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  64068. }
  64069. }
  64070. };
  64071. Sound.prototype._onended = function () {
  64072. this.isPlaying = false;
  64073. if (this.onended) {
  64074. this.onended();
  64075. }
  64076. };
  64077. /**
  64078. * Stop the sound
  64079. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  64080. */
  64081. Sound.prototype.stop = function (time) {
  64082. if (this.isPlaying) {
  64083. if (this._streaming) {
  64084. if (this._htmlAudioElement) {
  64085. this._htmlAudioElement.pause();
  64086. // Test needed for Firefox or it will generate an Invalid State Error
  64087. if (this._htmlAudioElement.currentTime > 0) {
  64088. this._htmlAudioElement.currentTime = 0;
  64089. }
  64090. }
  64091. else {
  64092. this._streamingSource.disconnect();
  64093. }
  64094. }
  64095. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  64096. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64097. this._soundSource.stop(stopTime);
  64098. this._soundSource.onended = function () { };
  64099. if (!this.isPaused) {
  64100. this._startOffset = 0;
  64101. }
  64102. }
  64103. this.isPlaying = false;
  64104. }
  64105. };
  64106. Sound.prototype.pause = function () {
  64107. if (this.isPlaying) {
  64108. this.isPaused = true;
  64109. if (this._streaming) {
  64110. if (this._htmlAudioElement) {
  64111. this._htmlAudioElement.pause();
  64112. }
  64113. else {
  64114. this._streamingSource.disconnect();
  64115. }
  64116. }
  64117. else if (BABYLON.Engine.audioEngine.audioContext) {
  64118. this.stop(0);
  64119. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  64120. }
  64121. }
  64122. };
  64123. Sound.prototype.setVolume = function (newVolume, time) {
  64124. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  64125. if (time && BABYLON.Engine.audioEngine.audioContext) {
  64126. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  64127. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  64128. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  64129. }
  64130. else {
  64131. this._soundGain.gain.value = newVolume;
  64132. }
  64133. }
  64134. this._volume = newVolume;
  64135. };
  64136. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  64137. this._playbackRate = newPlaybackRate;
  64138. if (this.isPlaying) {
  64139. if (this._streaming && this._htmlAudioElement) {
  64140. this._htmlAudioElement.playbackRate = this._playbackRate;
  64141. }
  64142. else if (this._soundSource) {
  64143. this._soundSource.playbackRate.value = this._playbackRate;
  64144. }
  64145. }
  64146. };
  64147. Sound.prototype.getVolume = function () {
  64148. return this._volume;
  64149. };
  64150. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  64151. var _this = this;
  64152. if (this._connectedMesh && this._registerFunc) {
  64153. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64154. this._registerFunc = null;
  64155. }
  64156. this._connectedMesh = meshToConnectTo;
  64157. if (!this.spatialSound) {
  64158. this.spatialSound = true;
  64159. this._createSpatialParameters();
  64160. if (this.isPlaying && this.loop) {
  64161. this.stop();
  64162. this.play();
  64163. }
  64164. }
  64165. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  64166. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  64167. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  64168. };
  64169. Sound.prototype.detachFromMesh = function () {
  64170. if (this._connectedMesh && this._registerFunc) {
  64171. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64172. this._registerFunc = null;
  64173. this._connectedMesh = null;
  64174. }
  64175. };
  64176. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  64177. if (!node.getBoundingInfo) {
  64178. return;
  64179. }
  64180. var mesh = node;
  64181. var boundingInfo = mesh.getBoundingInfo();
  64182. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  64183. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  64184. this._updateDirection();
  64185. }
  64186. };
  64187. Sound.prototype.clone = function () {
  64188. var _this = this;
  64189. if (!this._streaming) {
  64190. var setBufferAndRun = function () {
  64191. if (_this._isReadyToPlay) {
  64192. clonedSound._audioBuffer = _this.getAudioBuffer();
  64193. clonedSound._isReadyToPlay = true;
  64194. if (clonedSound.autoplay) {
  64195. clonedSound.play();
  64196. }
  64197. }
  64198. else {
  64199. window.setTimeout(setBufferAndRun, 300);
  64200. }
  64201. };
  64202. var currentOptions = {
  64203. autoplay: this.autoplay, loop: this.loop,
  64204. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  64205. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  64206. refDistance: this.refDistance, distanceModel: this.distanceModel
  64207. };
  64208. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  64209. if (this.useCustomAttenuation) {
  64210. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  64211. }
  64212. clonedSound.setPosition(this._position);
  64213. clonedSound.setPlaybackRate(this._playbackRate);
  64214. setBufferAndRun();
  64215. return clonedSound;
  64216. }
  64217. // Can't clone a streaming sound
  64218. else {
  64219. return null;
  64220. }
  64221. };
  64222. Sound.prototype.getAudioBuffer = function () {
  64223. return this._audioBuffer;
  64224. };
  64225. Sound.prototype.serialize = function () {
  64226. var serializationObject = {
  64227. name: this.name,
  64228. url: this.name,
  64229. autoplay: this.autoplay,
  64230. loop: this.loop,
  64231. volume: this._volume,
  64232. spatialSound: this.spatialSound,
  64233. maxDistance: this.maxDistance,
  64234. rolloffFactor: this.rolloffFactor,
  64235. refDistance: this.refDistance,
  64236. distanceModel: this.distanceModel,
  64237. playbackRate: this._playbackRate,
  64238. panningModel: this._panningModel,
  64239. soundTrackId: this.soundTrackId
  64240. };
  64241. if (this.spatialSound) {
  64242. if (this._connectedMesh)
  64243. serializationObject.connectedMeshId = this._connectedMesh.id;
  64244. serializationObject.position = this._position.asArray();
  64245. serializationObject.refDistance = this.refDistance;
  64246. serializationObject.distanceModel = this.distanceModel;
  64247. serializationObject.isDirectional = this._isDirectional;
  64248. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  64249. serializationObject.coneInnerAngle = this._coneInnerAngle;
  64250. serializationObject.coneOuterAngle = this._coneOuterAngle;
  64251. serializationObject.coneOuterGain = this._coneOuterGain;
  64252. }
  64253. return serializationObject;
  64254. };
  64255. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  64256. var soundName = parsedSound.name;
  64257. var soundUrl;
  64258. if (parsedSound.url) {
  64259. soundUrl = rootUrl + parsedSound.url;
  64260. }
  64261. else {
  64262. soundUrl = rootUrl + soundName;
  64263. }
  64264. var options = {
  64265. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  64266. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  64267. rolloffFactor: parsedSound.rolloffFactor,
  64268. refDistance: parsedSound.refDistance,
  64269. distanceModel: parsedSound.distanceModel,
  64270. playbackRate: parsedSound.playbackRate
  64271. };
  64272. var newSound;
  64273. if (!sourceSound) {
  64274. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  64275. scene._addPendingData(newSound);
  64276. }
  64277. else {
  64278. var setBufferAndRun = function () {
  64279. if (sourceSound._isReadyToPlay) {
  64280. newSound._audioBuffer = sourceSound.getAudioBuffer();
  64281. newSound._isReadyToPlay = true;
  64282. if (newSound.autoplay) {
  64283. newSound.play();
  64284. }
  64285. }
  64286. else {
  64287. window.setTimeout(setBufferAndRun, 300);
  64288. }
  64289. };
  64290. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  64291. setBufferAndRun();
  64292. }
  64293. if (parsedSound.position) {
  64294. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  64295. newSound.setPosition(soundPosition);
  64296. }
  64297. if (parsedSound.isDirectional) {
  64298. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  64299. if (parsedSound.localDirectionToMesh) {
  64300. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  64301. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  64302. }
  64303. }
  64304. if (parsedSound.connectedMeshId) {
  64305. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  64306. if (connectedMesh) {
  64307. newSound.attachToMesh(connectedMesh);
  64308. }
  64309. }
  64310. return newSound;
  64311. };
  64312. return Sound;
  64313. }());
  64314. BABYLON.Sound = Sound;
  64315. })(BABYLON || (BABYLON = {}));
  64316. //# sourceMappingURL=babylon.sound.js.map
  64317. var BABYLON;
  64318. (function (BABYLON) {
  64319. var SoundTrack = /** @class */ (function () {
  64320. function SoundTrack(scene, options) {
  64321. this.id = -1;
  64322. this._isMainTrack = false;
  64323. this._isInitialized = false;
  64324. this._scene = scene;
  64325. this.soundCollection = new Array();
  64326. this._options = options;
  64327. if (!this._isMainTrack) {
  64328. this._scene.soundTracks.push(this);
  64329. this.id = this._scene.soundTracks.length - 1;
  64330. }
  64331. }
  64332. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  64333. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64334. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  64335. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  64336. if (this._options) {
  64337. if (this._options.volume) {
  64338. this._outputAudioNode.gain.value = this._options.volume;
  64339. }
  64340. if (this._options.mainTrack) {
  64341. this._isMainTrack = this._options.mainTrack;
  64342. }
  64343. }
  64344. this._isInitialized = true;
  64345. }
  64346. };
  64347. SoundTrack.prototype.dispose = function () {
  64348. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  64349. if (this._connectedAnalyser) {
  64350. this._connectedAnalyser.stopDebugCanvas();
  64351. }
  64352. while (this.soundCollection.length) {
  64353. this.soundCollection[0].dispose();
  64354. }
  64355. if (this._outputAudioNode) {
  64356. this._outputAudioNode.disconnect();
  64357. }
  64358. this._outputAudioNode = null;
  64359. }
  64360. };
  64361. SoundTrack.prototype.AddSound = function (sound) {
  64362. if (!this._isInitialized) {
  64363. this._initializeSoundTrackAudioGraph();
  64364. }
  64365. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64366. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  64367. }
  64368. if (sound.soundTrackId) {
  64369. if (sound.soundTrackId === -1) {
  64370. this._scene.mainSoundTrack.RemoveSound(sound);
  64371. }
  64372. else {
  64373. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  64374. }
  64375. }
  64376. this.soundCollection.push(sound);
  64377. sound.soundTrackId = this.id;
  64378. };
  64379. SoundTrack.prototype.RemoveSound = function (sound) {
  64380. var index = this.soundCollection.indexOf(sound);
  64381. if (index !== -1) {
  64382. this.soundCollection.splice(index, 1);
  64383. }
  64384. };
  64385. SoundTrack.prototype.setVolume = function (newVolume) {
  64386. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64387. this._outputAudioNode.gain.value = newVolume;
  64388. }
  64389. };
  64390. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  64391. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64392. for (var i = 0; i < this.soundCollection.length; i++) {
  64393. this.soundCollection[i].switchPanningModelToHRTF();
  64394. }
  64395. }
  64396. };
  64397. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  64398. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64399. for (var i = 0; i < this.soundCollection.length; i++) {
  64400. this.soundCollection[i].switchPanningModelToEqualPower();
  64401. }
  64402. }
  64403. };
  64404. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  64405. if (this._connectedAnalyser) {
  64406. this._connectedAnalyser.stopDebugCanvas();
  64407. }
  64408. this._connectedAnalyser = analyser;
  64409. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64410. this._outputAudioNode.disconnect();
  64411. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  64412. }
  64413. };
  64414. return SoundTrack;
  64415. }());
  64416. BABYLON.SoundTrack = SoundTrack;
  64417. })(BABYLON || (BABYLON = {}));
  64418. //# sourceMappingURL=babylon.soundtrack.js.map
  64419. var BABYLON;
  64420. (function (BABYLON) {
  64421. /**
  64422. * Class used to work with sound analyzer using fast fourier transform (FFT)
  64423. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  64424. */
  64425. var Analyser = /** @class */ (function () {
  64426. /**
  64427. * Creates a new analyser
  64428. * @param scene defines hosting scene
  64429. */
  64430. function Analyser(scene) {
  64431. /**
  64432. * Gets or sets the smoothing
  64433. * @ignorenaming
  64434. */
  64435. this.SMOOTHING = 0.75;
  64436. /**
  64437. * Gets or sets the FFT table size
  64438. * @ignorenaming
  64439. */
  64440. this.FFT_SIZE = 512;
  64441. /**
  64442. * Gets or sets the bar graph amplitude
  64443. * @ignorenaming
  64444. */
  64445. this.BARGRAPHAMPLITUDE = 256;
  64446. /**
  64447. * Gets or sets the position of the debug canvas
  64448. * @ignorenaming
  64449. */
  64450. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  64451. /**
  64452. * Gets or sets the debug canvas size
  64453. * @ignorenaming
  64454. */
  64455. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  64456. this._scene = scene;
  64457. this._audioEngine = BABYLON.Engine.audioEngine;
  64458. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  64459. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  64460. this._webAudioAnalyser.minDecibels = -140;
  64461. this._webAudioAnalyser.maxDecibels = 0;
  64462. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64463. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64464. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  64465. }
  64466. }
  64467. /**
  64468. * Get the number of data values you will have to play with for the visualization
  64469. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  64470. * @returns a number
  64471. */
  64472. Analyser.prototype.getFrequencyBinCount = function () {
  64473. if (this._audioEngine.canUseWebAudio) {
  64474. return this._webAudioAnalyser.frequencyBinCount;
  64475. }
  64476. else {
  64477. return 0;
  64478. }
  64479. };
  64480. /**
  64481. * Gets the current frequency data as a byte array
  64482. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64483. * @returns a Uint8Array
  64484. */
  64485. Analyser.prototype.getByteFrequencyData = function () {
  64486. if (this._audioEngine.canUseWebAudio) {
  64487. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64488. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64489. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  64490. }
  64491. return this._byteFreqs;
  64492. };
  64493. /**
  64494. * Gets the current waveform as a byte array
  64495. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  64496. * @returns a Uint8Array
  64497. */
  64498. Analyser.prototype.getByteTimeDomainData = function () {
  64499. if (this._audioEngine.canUseWebAudio) {
  64500. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64501. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64502. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  64503. }
  64504. return this._byteTime;
  64505. };
  64506. /**
  64507. * Gets the current frequency data as a float array
  64508. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64509. * @returns a Float32Array
  64510. */
  64511. Analyser.prototype.getFloatFrequencyData = function () {
  64512. if (this._audioEngine.canUseWebAudio) {
  64513. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64514. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64515. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  64516. }
  64517. return this._floatFreqs;
  64518. };
  64519. /**
  64520. * Renders the debug canvas
  64521. */
  64522. Analyser.prototype.drawDebugCanvas = function () {
  64523. var _this = this;
  64524. if (this._audioEngine.canUseWebAudio) {
  64525. if (!this._debugCanvas) {
  64526. this._debugCanvas = document.createElement("canvas");
  64527. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  64528. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  64529. this._debugCanvas.style.position = "absolute";
  64530. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  64531. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  64532. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  64533. document.body.appendChild(this._debugCanvas);
  64534. this._registerFunc = function () {
  64535. _this.drawDebugCanvas();
  64536. };
  64537. this._scene.registerBeforeRender(this._registerFunc);
  64538. }
  64539. if (this._registerFunc && this._debugCanvasContext) {
  64540. var workingArray = this.getByteFrequencyData();
  64541. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  64542. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  64543. // Draw the frequency domain chart.
  64544. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  64545. var value = workingArray[i];
  64546. var percent = value / this.BARGRAPHAMPLITUDE;
  64547. var height = this.DEBUGCANVASSIZE.height * percent;
  64548. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  64549. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  64550. var hue = i / this.getFrequencyBinCount() * 360;
  64551. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  64552. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  64553. }
  64554. }
  64555. }
  64556. };
  64557. /**
  64558. * Stops rendering the debug canvas and removes it
  64559. */
  64560. Analyser.prototype.stopDebugCanvas = function () {
  64561. if (this._debugCanvas) {
  64562. if (this._registerFunc) {
  64563. this._scene.unregisterBeforeRender(this._registerFunc);
  64564. this._registerFunc = null;
  64565. }
  64566. document.body.removeChild(this._debugCanvas);
  64567. this._debugCanvas = null;
  64568. this._debugCanvasContext = null;
  64569. }
  64570. };
  64571. /**
  64572. * Connects two audio nodes
  64573. * @param inputAudioNode defines first node to connect
  64574. * @param outputAudioNode defines second node to connect
  64575. */
  64576. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  64577. if (this._audioEngine.canUseWebAudio) {
  64578. inputAudioNode.connect(this._webAudioAnalyser);
  64579. this._webAudioAnalyser.connect(outputAudioNode);
  64580. }
  64581. };
  64582. /**
  64583. * Releases all associated resources
  64584. */
  64585. Analyser.prototype.dispose = function () {
  64586. if (this._audioEngine.canUseWebAudio) {
  64587. this._webAudioAnalyser.disconnect();
  64588. }
  64589. };
  64590. return Analyser;
  64591. }());
  64592. BABYLON.Analyser = Analyser;
  64593. })(BABYLON || (BABYLON = {}));
  64594. //# sourceMappingURL=babylon.analyser.js.map
  64595. var BABYLON;
  64596. (function (BABYLON) {
  64597. var CubeTexture = /** @class */ (function (_super) {
  64598. __extends(CubeTexture, _super);
  64599. /**
  64600. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  64601. * as prefiltered data.
  64602. * @param rootUrl defines the url of the texture or the root name of the six images
  64603. * @param scene defines the scene the texture is attached to
  64604. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  64605. * @param noMipmap defines if mipmaps should be created or not
  64606. * @param files defines the six files to load for the different faces
  64607. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  64608. * @param onError defines a callback triggered in case of error during load
  64609. * @param format defines the internal format to use for the texture once loaded
  64610. * @param prefiltered defines whether or not the texture is created from prefiltered data
  64611. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  64612. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64613. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64614. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64615. * @return the cube texture
  64616. */
  64617. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  64618. if (extensions === void 0) { extensions = null; }
  64619. if (noMipmap === void 0) { noMipmap = false; }
  64620. if (files === void 0) { files = null; }
  64621. if (onLoad === void 0) { onLoad = null; }
  64622. if (onError === void 0) { onError = null; }
  64623. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64624. if (prefiltered === void 0) { prefiltered = false; }
  64625. if (forcedExtension === void 0) { forcedExtension = null; }
  64626. if (createPolynomials === void 0) { createPolynomials = false; }
  64627. if (lodScale === void 0) { lodScale = 0.8; }
  64628. if (lodOffset === void 0) { lodOffset = 0; }
  64629. var _this = _super.call(this, scene) || this;
  64630. /**
  64631. * Gets or sets the center of the bounding box associated with the cube texture
  64632. * It must define where the camera used to render the texture was set
  64633. */
  64634. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  64635. _this._rotationY = 0;
  64636. /** @hidden */
  64637. _this._prefiltered = false;
  64638. _this.name = rootUrl;
  64639. _this.url = rootUrl;
  64640. _this._noMipmap = noMipmap;
  64641. _this.hasAlpha = false;
  64642. _this._format = format;
  64643. _this.isCube = true;
  64644. _this._textureMatrix = BABYLON.Matrix.Identity();
  64645. _this._createPolynomials = createPolynomials;
  64646. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  64647. if (!rootUrl && !files) {
  64648. return _this;
  64649. }
  64650. var lastDot = rootUrl.lastIndexOf(".");
  64651. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  64652. var isDDS = (extension === ".dds");
  64653. var isEnv = (extension === ".env");
  64654. if (isEnv) {
  64655. _this.gammaSpace = false;
  64656. _this._prefiltered = false;
  64657. }
  64658. else {
  64659. _this._prefiltered = prefiltered;
  64660. if (prefiltered) {
  64661. _this.gammaSpace = false;
  64662. }
  64663. }
  64664. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  64665. if (!files) {
  64666. if (!isEnv && !isDDS && !extensions) {
  64667. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  64668. }
  64669. files = [];
  64670. if (extensions) {
  64671. for (var index = 0; index < extensions.length; index++) {
  64672. files.push(rootUrl + extensions[index]);
  64673. }
  64674. }
  64675. }
  64676. _this._files = files;
  64677. if (!_this._texture) {
  64678. if (!scene.useDelayedTextureLoading) {
  64679. if (prefiltered) {
  64680. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  64681. }
  64682. else {
  64683. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  64684. }
  64685. }
  64686. else {
  64687. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64688. }
  64689. }
  64690. else if (onLoad) {
  64691. if (_this._texture.isReady) {
  64692. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  64693. }
  64694. else {
  64695. _this._texture.onLoadedObservable.add(onLoad);
  64696. }
  64697. }
  64698. return _this;
  64699. }
  64700. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  64701. get: function () {
  64702. return this._boundingBoxSize;
  64703. },
  64704. /**
  64705. * Gets or sets the size of the bounding box associated with the cube texture
  64706. * When defined, the cubemap will switch to local mode
  64707. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64708. * @example https://www.babylonjs-playground.com/#RNASML
  64709. */
  64710. set: function (value) {
  64711. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64712. return;
  64713. }
  64714. this._boundingBoxSize = value;
  64715. var scene = this.getScene();
  64716. if (scene) {
  64717. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64718. }
  64719. },
  64720. enumerable: true,
  64721. configurable: true
  64722. });
  64723. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  64724. /**
  64725. * Gets texture matrix rotation angle around Y axis radians.
  64726. */
  64727. get: function () {
  64728. return this._rotationY;
  64729. },
  64730. /**
  64731. * Sets texture matrix rotation angle around Y axis in radians.
  64732. */
  64733. set: function (value) {
  64734. this._rotationY = value;
  64735. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  64736. },
  64737. enumerable: true,
  64738. configurable: true
  64739. });
  64740. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  64741. var rootUrlKey = "";
  64742. files.forEach(function (url) { return rootUrlKey += url; });
  64743. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  64744. };
  64745. /**
  64746. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  64747. * @param url defines the url of the prefiltered texture
  64748. * @param scene defines the scene the texture is attached to
  64749. * @param forcedExtension defines the extension of the file if different from the url
  64750. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64751. * @return the prefiltered texture
  64752. */
  64753. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  64754. if (forcedExtension === void 0) { forcedExtension = null; }
  64755. if (createPolynomials === void 0) { createPolynomials = true; }
  64756. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  64757. };
  64758. // Methods
  64759. CubeTexture.prototype.delayLoad = function () {
  64760. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64761. return;
  64762. }
  64763. var scene = this.getScene();
  64764. if (!scene) {
  64765. return;
  64766. }
  64767. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64768. this._texture = this._getFromCache(this.url, this._noMipmap);
  64769. if (!this._texture) {
  64770. if (this._prefiltered) {
  64771. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  64772. }
  64773. else {
  64774. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  64775. }
  64776. }
  64777. };
  64778. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  64779. return this._textureMatrix;
  64780. };
  64781. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64782. this._textureMatrix = value;
  64783. };
  64784. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64785. var texture = BABYLON.SerializationHelper.Parse(function () {
  64786. var prefiltered = false;
  64787. if (parsedTexture.prefiltered) {
  64788. prefiltered = parsedTexture.prefiltered;
  64789. }
  64790. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  64791. }, parsedTexture, scene);
  64792. // Local Cubemaps
  64793. if (parsedTexture.boundingBoxPosition) {
  64794. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  64795. }
  64796. if (parsedTexture.boundingBoxSize) {
  64797. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  64798. }
  64799. // Animations
  64800. if (parsedTexture.animations) {
  64801. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  64802. var parsedAnimation = parsedTexture.animations[animationIndex];
  64803. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  64804. }
  64805. }
  64806. return texture;
  64807. };
  64808. CubeTexture.prototype.clone = function () {
  64809. var _this = this;
  64810. return BABYLON.SerializationHelper.Clone(function () {
  64811. var scene = _this.getScene();
  64812. if (!scene) {
  64813. return _this;
  64814. }
  64815. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  64816. }, this);
  64817. };
  64818. __decorate([
  64819. BABYLON.serialize("rotationY")
  64820. ], CubeTexture.prototype, "_rotationY", void 0);
  64821. return CubeTexture;
  64822. }(BABYLON.BaseTexture));
  64823. BABYLON.CubeTexture = CubeTexture;
  64824. })(BABYLON || (BABYLON = {}));
  64825. //# sourceMappingURL=babylon.cubeTexture.js.map
  64826. var BABYLON;
  64827. (function (BABYLON) {
  64828. /**
  64829. * Raw cube texture where the raw buffers are passed in
  64830. */
  64831. var RawCubeTexture = /** @class */ (function (_super) {
  64832. __extends(RawCubeTexture, _super);
  64833. /**
  64834. * Creates a cube texture where the raw buffers are passed in.
  64835. * @param scene defines the scene the texture is attached to
  64836. * @param data defines the array of data to use to create each face
  64837. * @param size defines the size of the textures
  64838. * @param format defines the format of the data
  64839. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  64840. * @param generateMipMaps defines if the engine should generate the mip levels
  64841. * @param invertY defines if data must be stored with Y axis inverted
  64842. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  64843. * @param compression defines the compression used (null by default)
  64844. */
  64845. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  64846. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64847. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64848. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64849. if (invertY === void 0) { invertY = false; }
  64850. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64851. if (compression === void 0) { compression = null; }
  64852. var _this = _super.call(this, "", scene) || this;
  64853. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  64854. return _this;
  64855. }
  64856. /**
  64857. * Updates the raw cube texture.
  64858. * @param data defines the data to store
  64859. * @param format defines the data format
  64860. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  64861. * @param invertY defines if data must be stored with Y axis inverted
  64862. * @param compression defines the compression used (null by default)
  64863. * @param level defines which level of the texture to update
  64864. */
  64865. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  64866. if (compression === void 0) { compression = null; }
  64867. if (level === void 0) { level = 0; }
  64868. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  64869. };
  64870. /**
  64871. * Updates a raw cube texture with RGBD encoded data.
  64872. * @param data defines the array of data [mipmap][face] to use to create each face
  64873. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  64874. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64875. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64876. * @returns a promsie that resolves when the operation is complete
  64877. */
  64878. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  64879. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  64880. if (lodScale === void 0) { lodScale = 0.8; }
  64881. if (lodOffset === void 0) { lodOffset = 0; }
  64882. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  64883. };
  64884. /**
  64885. * Clones the raw cube texture.
  64886. * @return a new cube texture
  64887. */
  64888. RawCubeTexture.prototype.clone = function () {
  64889. var _this = this;
  64890. return BABYLON.SerializationHelper.Clone(function () {
  64891. var scene = _this.getScene();
  64892. var internalTexture = _this._texture;
  64893. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  64894. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  64895. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  64896. }
  64897. return texture;
  64898. }, this);
  64899. };
  64900. /** @hidden */
  64901. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  64902. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  64903. internalTexture._bufferViewArrayArray = data;
  64904. internalTexture._lodGenerationScale = lodScale;
  64905. internalTexture._lodGenerationOffset = lodOffset;
  64906. internalTexture._sphericalPolynomial = sphericalPolynomial;
  64907. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  64908. internalTexture.isReady = true;
  64909. });
  64910. };
  64911. return RawCubeTexture;
  64912. }(BABYLON.CubeTexture));
  64913. BABYLON.RawCubeTexture = RawCubeTexture;
  64914. })(BABYLON || (BABYLON = {}));
  64915. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  64916. var BABYLON;
  64917. (function (BABYLON) {
  64918. var RenderTargetTexture = /** @class */ (function (_super) {
  64919. __extends(RenderTargetTexture, _super);
  64920. /**
  64921. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  64922. * or used a shadow, depth texture...
  64923. * @param name The friendly name of the texture
  64924. * @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)
  64925. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  64926. * @param generateMipMaps True if mip maps need to be generated after render.
  64927. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  64928. * @param type The type of the buffer in the RTT (int, half float, float...)
  64929. * @param isCube True if a cube texture needs to be created
  64930. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  64931. * @param generateDepthBuffer True to generate a depth buffer
  64932. * @param generateStencilBuffer True to generate a stencil buffer
  64933. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  64934. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  64935. */
  64936. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  64937. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  64938. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64939. if (isCube === void 0) { isCube = false; }
  64940. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64941. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64942. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  64943. if (isMulti === void 0) { isMulti = false; }
  64944. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64945. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64946. _this.isCube = isCube;
  64947. /**
  64948. * Use this list to define the list of mesh you want to render.
  64949. */
  64950. _this.renderList = new Array();
  64951. _this.renderParticles = true;
  64952. _this.renderSprites = false;
  64953. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  64954. _this.ignoreCameraViewport = false;
  64955. // Events
  64956. /**
  64957. * An event triggered when the texture is unbind.
  64958. */
  64959. _this.onBeforeBindObservable = new BABYLON.Observable();
  64960. /**
  64961. * An event triggered when the texture is unbind.
  64962. */
  64963. _this.onAfterUnbindObservable = new BABYLON.Observable();
  64964. /**
  64965. * An event triggered before rendering the texture
  64966. */
  64967. _this.onBeforeRenderObservable = new BABYLON.Observable();
  64968. /**
  64969. * An event triggered after rendering the texture
  64970. */
  64971. _this.onAfterRenderObservable = new BABYLON.Observable();
  64972. /**
  64973. * An event triggered after the texture clear
  64974. */
  64975. _this.onClearObservable = new BABYLON.Observable();
  64976. _this._currentRefreshId = -1;
  64977. _this._refreshRate = 1;
  64978. _this._samples = 1;
  64979. /**
  64980. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  64981. * It must define where the camera used to render the texture is set
  64982. */
  64983. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  64984. scene = _this.getScene();
  64985. if (!scene) {
  64986. return _this;
  64987. }
  64988. _this._engine = scene.getEngine();
  64989. _this.name = name;
  64990. _this.isRenderTarget = true;
  64991. _this._initialSizeParameter = size;
  64992. _this._processSizeParameter(size);
  64993. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  64994. });
  64995. _this._generateMipMaps = generateMipMaps ? true : false;
  64996. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  64997. // Rendering groups
  64998. _this._renderingManager = new BABYLON.RenderingManager(scene);
  64999. _this._renderingManager._useSceneAutoClearSetup = true;
  65000. if (isMulti) {
  65001. return _this;
  65002. }
  65003. _this._renderTargetOptions = {
  65004. generateMipMaps: generateMipMaps,
  65005. type: type,
  65006. format: format,
  65007. samplingMode: samplingMode,
  65008. generateDepthBuffer: generateDepthBuffer,
  65009. generateStencilBuffer: generateStencilBuffer
  65010. };
  65011. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  65012. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65013. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65014. }
  65015. if (isCube) {
  65016. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  65017. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  65018. _this._textureMatrix = BABYLON.Matrix.Identity();
  65019. }
  65020. else {
  65021. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  65022. }
  65023. return _this;
  65024. }
  65025. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  65026. get: function () {
  65027. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  65028. },
  65029. enumerable: true,
  65030. configurable: true
  65031. });
  65032. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  65033. get: function () {
  65034. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  65035. },
  65036. enumerable: true,
  65037. configurable: true
  65038. });
  65039. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  65040. get: function () {
  65041. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  65042. },
  65043. enumerable: true,
  65044. configurable: true
  65045. });
  65046. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  65047. set: function (callback) {
  65048. if (this._onAfterUnbindObserver) {
  65049. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  65050. }
  65051. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  65052. },
  65053. enumerable: true,
  65054. configurable: true
  65055. });
  65056. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  65057. set: function (callback) {
  65058. if (this._onBeforeRenderObserver) {
  65059. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65060. }
  65061. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65062. },
  65063. enumerable: true,
  65064. configurable: true
  65065. });
  65066. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  65067. set: function (callback) {
  65068. if (this._onAfterRenderObserver) {
  65069. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65070. }
  65071. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65072. },
  65073. enumerable: true,
  65074. configurable: true
  65075. });
  65076. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  65077. set: function (callback) {
  65078. if (this._onClearObserver) {
  65079. this.onClearObservable.remove(this._onClearObserver);
  65080. }
  65081. this._onClearObserver = this.onClearObservable.add(callback);
  65082. },
  65083. enumerable: true,
  65084. configurable: true
  65085. });
  65086. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  65087. get: function () {
  65088. return this._renderTargetOptions;
  65089. },
  65090. enumerable: true,
  65091. configurable: true
  65092. });
  65093. RenderTargetTexture.prototype._onRatioRescale = function () {
  65094. if (this._sizeRatio) {
  65095. this.resize(this._initialSizeParameter);
  65096. }
  65097. };
  65098. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  65099. get: function () {
  65100. return this._boundingBoxSize;
  65101. },
  65102. /**
  65103. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  65104. * When defined, the cubemap will switch to local mode
  65105. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65106. * @example https://www.babylonjs-playground.com/#RNASML
  65107. */
  65108. set: function (value) {
  65109. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65110. return;
  65111. }
  65112. this._boundingBoxSize = value;
  65113. var scene = this.getScene();
  65114. if (scene) {
  65115. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65116. }
  65117. },
  65118. enumerable: true,
  65119. configurable: true
  65120. });
  65121. /**
  65122. * Creates a depth stencil texture.
  65123. * This is only available in WebGL 2 or with the depth texture extension available.
  65124. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  65125. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  65126. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  65127. */
  65128. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  65129. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  65130. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  65131. if (generateStencil === void 0) { generateStencil = false; }
  65132. if (!this.getScene()) {
  65133. return;
  65134. }
  65135. var engine = this.getScene().getEngine();
  65136. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  65137. bilinearFiltering: bilinearFiltering,
  65138. comparisonFunction: comparisonFunction,
  65139. generateStencil: generateStencil,
  65140. isCube: this.isCube
  65141. });
  65142. engine.setFrameBufferDepthStencilTexture(this);
  65143. };
  65144. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  65145. if (size.ratio) {
  65146. this._sizeRatio = size.ratio;
  65147. this._size = {
  65148. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  65149. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  65150. };
  65151. }
  65152. else {
  65153. this._size = size;
  65154. }
  65155. };
  65156. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  65157. get: function () {
  65158. return this._samples;
  65159. },
  65160. set: function (value) {
  65161. if (this._samples === value) {
  65162. return;
  65163. }
  65164. var scene = this.getScene();
  65165. if (!scene) {
  65166. return;
  65167. }
  65168. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  65169. },
  65170. enumerable: true,
  65171. configurable: true
  65172. });
  65173. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  65174. this._currentRefreshId = -1;
  65175. };
  65176. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  65177. get: function () {
  65178. return this._refreshRate;
  65179. },
  65180. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65181. set: function (value) {
  65182. this._refreshRate = value;
  65183. this.resetRefreshCounter();
  65184. },
  65185. enumerable: true,
  65186. configurable: true
  65187. });
  65188. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  65189. if (!this._postProcessManager) {
  65190. var scene = this.getScene();
  65191. if (!scene) {
  65192. return;
  65193. }
  65194. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  65195. this._postProcesses = new Array();
  65196. }
  65197. this._postProcesses.push(postProcess);
  65198. this._postProcesses[0].autoClear = false;
  65199. };
  65200. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  65201. if (!this._postProcesses) {
  65202. return;
  65203. }
  65204. if (dispose) {
  65205. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  65206. var postProcess = _a[_i];
  65207. postProcess.dispose();
  65208. }
  65209. }
  65210. this._postProcesses = [];
  65211. };
  65212. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  65213. if (!this._postProcesses) {
  65214. return;
  65215. }
  65216. var index = this._postProcesses.indexOf(postProcess);
  65217. if (index === -1) {
  65218. return;
  65219. }
  65220. this._postProcesses.splice(index, 1);
  65221. if (this._postProcesses.length > 0) {
  65222. this._postProcesses[0].autoClear = false;
  65223. }
  65224. };
  65225. RenderTargetTexture.prototype._shouldRender = function () {
  65226. if (this._currentRefreshId === -1) { // At least render once
  65227. this._currentRefreshId = 1;
  65228. return true;
  65229. }
  65230. if (this.refreshRate === this._currentRefreshId) {
  65231. this._currentRefreshId = 1;
  65232. return true;
  65233. }
  65234. this._currentRefreshId++;
  65235. return false;
  65236. };
  65237. RenderTargetTexture.prototype.getRenderSize = function () {
  65238. if (this._size.width) {
  65239. return this._size.width;
  65240. }
  65241. return this._size;
  65242. };
  65243. RenderTargetTexture.prototype.getRenderWidth = function () {
  65244. if (this._size.width) {
  65245. return this._size.width;
  65246. }
  65247. return this._size;
  65248. };
  65249. RenderTargetTexture.prototype.getRenderHeight = function () {
  65250. if (this._size.width) {
  65251. return this._size.height;
  65252. }
  65253. return this._size;
  65254. };
  65255. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  65256. get: function () {
  65257. return true;
  65258. },
  65259. enumerable: true,
  65260. configurable: true
  65261. });
  65262. RenderTargetTexture.prototype.scale = function (ratio) {
  65263. var newSize = this.getRenderSize() * ratio;
  65264. this.resize(newSize);
  65265. };
  65266. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  65267. if (this.isCube) {
  65268. return this._textureMatrix;
  65269. }
  65270. return _super.prototype.getReflectionTextureMatrix.call(this);
  65271. };
  65272. RenderTargetTexture.prototype.resize = function (size) {
  65273. this.releaseInternalTexture();
  65274. var scene = this.getScene();
  65275. if (!scene) {
  65276. return;
  65277. }
  65278. this._processSizeParameter(size);
  65279. if (this.isCube) {
  65280. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  65281. }
  65282. else {
  65283. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  65284. }
  65285. };
  65286. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  65287. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  65288. if (dumpForDebug === void 0) { dumpForDebug = false; }
  65289. var scene = this.getScene();
  65290. if (!scene) {
  65291. return;
  65292. }
  65293. var engine = scene.getEngine();
  65294. if (this.useCameraPostProcesses !== undefined) {
  65295. useCameraPostProcess = this.useCameraPostProcesses;
  65296. }
  65297. if (this._waitingRenderList) {
  65298. this.renderList = [];
  65299. for (var index = 0; index < this._waitingRenderList.length; index++) {
  65300. var id = this._waitingRenderList[index];
  65301. var mesh_1 = scene.getMeshByID(id);
  65302. if (mesh_1) {
  65303. this.renderList.push(mesh_1);
  65304. }
  65305. }
  65306. delete this._waitingRenderList;
  65307. }
  65308. // Is predicate defined?
  65309. if (this.renderListPredicate) {
  65310. if (this.renderList) {
  65311. this.renderList.splice(0); // Clear previous renderList
  65312. }
  65313. else {
  65314. this.renderList = [];
  65315. }
  65316. var scene = this.getScene();
  65317. if (!scene) {
  65318. return;
  65319. }
  65320. var sceneMeshes = scene.meshes;
  65321. for (var index = 0; index < sceneMeshes.length; index++) {
  65322. var mesh = sceneMeshes[index];
  65323. if (this.renderListPredicate(mesh)) {
  65324. this.renderList.push(mesh);
  65325. }
  65326. }
  65327. }
  65328. this.onBeforeBindObservable.notifyObservers(this);
  65329. // Set custom projection.
  65330. // Needs to be before binding to prevent changing the aspect ratio.
  65331. var camera;
  65332. if (this.activeCamera) {
  65333. camera = this.activeCamera;
  65334. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65335. if (this.activeCamera !== scene.activeCamera) {
  65336. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  65337. }
  65338. }
  65339. else {
  65340. camera = scene.activeCamera;
  65341. if (camera) {
  65342. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65343. }
  65344. }
  65345. // Prepare renderingManager
  65346. this._renderingManager.reset();
  65347. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  65348. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  65349. var sceneRenderId = scene.getRenderId();
  65350. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  65351. var mesh = currentRenderList[meshIndex];
  65352. if (mesh) {
  65353. if (!mesh.isReady(this.refreshRate === 0)) {
  65354. this.resetRefreshCounter();
  65355. continue;
  65356. }
  65357. mesh._preActivateForIntermediateRendering(sceneRenderId);
  65358. var isMasked = void 0;
  65359. if (!this.renderList && camera) {
  65360. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  65361. }
  65362. else {
  65363. isMasked = false;
  65364. }
  65365. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  65366. mesh._activate(sceneRenderId);
  65367. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  65368. var subMesh = mesh.subMeshes[subIndex];
  65369. scene._activeIndices.addCount(subMesh.indexCount, false);
  65370. this._renderingManager.dispatch(subMesh, mesh);
  65371. }
  65372. }
  65373. }
  65374. }
  65375. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  65376. var particleSystem = scene.particleSystems[particleIndex];
  65377. var emitter = particleSystem.emitter;
  65378. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  65379. continue;
  65380. }
  65381. if (currentRenderList.indexOf(emitter) >= 0) {
  65382. this._renderingManager.dispatchParticles(particleSystem);
  65383. }
  65384. }
  65385. if (this.isCube) {
  65386. for (var face = 0; face < 6; face++) {
  65387. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65388. scene.incrementRenderId();
  65389. scene.resetCachedMaterial();
  65390. }
  65391. }
  65392. else {
  65393. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65394. }
  65395. this.onAfterUnbindObservable.notifyObservers(this);
  65396. if (scene.activeCamera) {
  65397. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  65398. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  65399. }
  65400. engine.setViewport(scene.activeCamera.viewport);
  65401. }
  65402. scene.resetCachedMaterial();
  65403. };
  65404. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  65405. var minimum = 128;
  65406. var x = renderDimension * scale;
  65407. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  65408. // Ensure we don't exceed the render dimension (while staying POT)
  65409. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  65410. };
  65411. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65412. var _this = this;
  65413. if (!this._texture) {
  65414. return;
  65415. }
  65416. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  65417. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65418. });
  65419. };
  65420. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  65421. var scene = this.getScene();
  65422. if (!scene) {
  65423. return;
  65424. }
  65425. var engine = scene.getEngine();
  65426. if (!this._texture) {
  65427. return;
  65428. }
  65429. // Bind
  65430. if (this._postProcessManager) {
  65431. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  65432. }
  65433. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  65434. if (this._texture) {
  65435. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  65436. }
  65437. }
  65438. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  65439. // Clear
  65440. if (this.onClearObservable.hasObservers()) {
  65441. this.onClearObservable.notifyObservers(engine);
  65442. }
  65443. else {
  65444. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  65445. }
  65446. if (!this._doNotChangeAspectRatio) {
  65447. scene.updateTransformMatrix(true);
  65448. }
  65449. // Render
  65450. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  65451. if (this._postProcessManager) {
  65452. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  65453. }
  65454. else if (useCameraPostProcess) {
  65455. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  65456. }
  65457. if (!this._doNotChangeAspectRatio) {
  65458. scene.updateTransformMatrix(true);
  65459. }
  65460. // Dump ?
  65461. if (dumpForDebug) {
  65462. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  65463. }
  65464. // Unbind
  65465. if (!this.isCube || faceIndex === 5) {
  65466. if (this.isCube) {
  65467. if (faceIndex === 5) {
  65468. engine.generateMipMapsForCubemap(this._texture);
  65469. }
  65470. }
  65471. this.unbindFrameBuffer(engine, faceIndex);
  65472. }
  65473. else {
  65474. this.onAfterRenderObservable.notifyObservers(faceIndex);
  65475. }
  65476. };
  65477. /**
  65478. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  65479. * This allowed control for front to back rendering or reversly depending of the special needs.
  65480. *
  65481. * @param renderingGroupId The rendering group id corresponding to its index
  65482. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  65483. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  65484. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  65485. */
  65486. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  65487. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  65488. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  65489. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  65490. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  65491. };
  65492. /**
  65493. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  65494. *
  65495. * @param renderingGroupId The rendering group id corresponding to its index
  65496. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  65497. */
  65498. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  65499. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  65500. this._renderingManager._useSceneAutoClearSetup = false;
  65501. };
  65502. RenderTargetTexture.prototype.clone = function () {
  65503. var textureSize = this.getSize();
  65504. 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);
  65505. // Base texture
  65506. newTexture.hasAlpha = this.hasAlpha;
  65507. newTexture.level = this.level;
  65508. // RenderTarget Texture
  65509. newTexture.coordinatesMode = this.coordinatesMode;
  65510. if (this.renderList) {
  65511. newTexture.renderList = this.renderList.slice(0);
  65512. }
  65513. return newTexture;
  65514. };
  65515. RenderTargetTexture.prototype.serialize = function () {
  65516. if (!this.name) {
  65517. return null;
  65518. }
  65519. var serializationObject = _super.prototype.serialize.call(this);
  65520. serializationObject.renderTargetSize = this.getRenderSize();
  65521. serializationObject.renderList = [];
  65522. if (this.renderList) {
  65523. for (var index = 0; index < this.renderList.length; index++) {
  65524. serializationObject.renderList.push(this.renderList[index].id);
  65525. }
  65526. }
  65527. return serializationObject;
  65528. };
  65529. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  65530. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  65531. var objBuffer = this.getInternalTexture();
  65532. var scene = this.getScene();
  65533. if (objBuffer && scene) {
  65534. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  65535. }
  65536. };
  65537. RenderTargetTexture.prototype.dispose = function () {
  65538. if (this._postProcessManager) {
  65539. this._postProcessManager.dispose();
  65540. this._postProcessManager = null;
  65541. }
  65542. this.clearPostProcesses(true);
  65543. if (this._resizeObserver) {
  65544. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  65545. this._resizeObserver = null;
  65546. }
  65547. this.renderList = null;
  65548. // Remove from custom render targets
  65549. var scene = this.getScene();
  65550. if (!scene) {
  65551. return;
  65552. }
  65553. var index = scene.customRenderTargets.indexOf(this);
  65554. if (index >= 0) {
  65555. scene.customRenderTargets.splice(index, 1);
  65556. }
  65557. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  65558. var camera = _a[_i];
  65559. index = camera.customRenderTargets.indexOf(this);
  65560. if (index >= 0) {
  65561. camera.customRenderTargets.splice(index, 1);
  65562. }
  65563. }
  65564. _super.prototype.dispose.call(this);
  65565. };
  65566. RenderTargetTexture.prototype._rebuild = function () {
  65567. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65568. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65569. }
  65570. if (this._postProcessManager) {
  65571. this._postProcessManager._rebuild();
  65572. }
  65573. };
  65574. /**
  65575. * Clear the info related to rendering groups preventing retention point in material dispose.
  65576. */
  65577. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  65578. if (this._renderingManager) {
  65579. this._renderingManager.freeRenderingGroups();
  65580. }
  65581. };
  65582. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  65583. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  65584. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  65585. return RenderTargetTexture;
  65586. }(BABYLON.Texture));
  65587. BABYLON.RenderTargetTexture = RenderTargetTexture;
  65588. })(BABYLON || (BABYLON = {}));
  65589. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  65590. var BABYLON;
  65591. (function (BABYLON) {
  65592. ;
  65593. var MultiRenderTarget = /** @class */ (function (_super) {
  65594. __extends(MultiRenderTarget, _super);
  65595. function MultiRenderTarget(name, size, count, scene, options) {
  65596. var _this = this;
  65597. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  65598. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  65599. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  65600. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  65601. _this._engine = scene.getEngine();
  65602. if (!_this.isSupported) {
  65603. _this.dispose();
  65604. return;
  65605. }
  65606. var types = [];
  65607. var samplingModes = [];
  65608. for (var i = 0; i < count; i++) {
  65609. if (options && options.types && options.types[i] !== undefined) {
  65610. types.push(options.types[i]);
  65611. }
  65612. else {
  65613. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65614. }
  65615. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  65616. samplingModes.push(options.samplingModes[i]);
  65617. }
  65618. else {
  65619. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65620. }
  65621. }
  65622. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  65623. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  65624. _this._size = size;
  65625. _this._multiRenderTargetOptions = {
  65626. samplingModes: samplingModes,
  65627. generateMipMaps: generateMipMaps,
  65628. generateDepthBuffer: generateDepthBuffer,
  65629. generateStencilBuffer: generateStencilBuffer,
  65630. generateDepthTexture: generateDepthTexture,
  65631. types: types,
  65632. textureCount: count
  65633. };
  65634. _this._createInternalTextures();
  65635. _this._createTextures();
  65636. return _this;
  65637. }
  65638. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  65639. get: function () {
  65640. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  65641. },
  65642. enumerable: true,
  65643. configurable: true
  65644. });
  65645. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  65646. get: function () {
  65647. return this._textures;
  65648. },
  65649. enumerable: true,
  65650. configurable: true
  65651. });
  65652. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  65653. get: function () {
  65654. return this._textures[this._textures.length - 1];
  65655. },
  65656. enumerable: true,
  65657. configurable: true
  65658. });
  65659. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  65660. set: function (wrap) {
  65661. if (this._textures) {
  65662. for (var i = 0; i < this._textures.length; i++) {
  65663. this._textures[i].wrapU = wrap;
  65664. }
  65665. }
  65666. },
  65667. enumerable: true,
  65668. configurable: true
  65669. });
  65670. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  65671. set: function (wrap) {
  65672. if (this._textures) {
  65673. for (var i = 0; i < this._textures.length; i++) {
  65674. this._textures[i].wrapV = wrap;
  65675. }
  65676. }
  65677. },
  65678. enumerable: true,
  65679. configurable: true
  65680. });
  65681. MultiRenderTarget.prototype._rebuild = function () {
  65682. this.releaseInternalTextures();
  65683. this._createInternalTextures();
  65684. for (var i = 0; i < this._internalTextures.length; i++) {
  65685. var texture = this._textures[i];
  65686. texture._texture = this._internalTextures[i];
  65687. }
  65688. // Keeps references to frame buffer and stencil/depth buffer
  65689. this._texture = this._internalTextures[0];
  65690. };
  65691. MultiRenderTarget.prototype._createInternalTextures = function () {
  65692. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  65693. };
  65694. MultiRenderTarget.prototype._createTextures = function () {
  65695. this._textures = [];
  65696. for (var i = 0; i < this._internalTextures.length; i++) {
  65697. var texture = new BABYLON.Texture(null, this.getScene());
  65698. texture._texture = this._internalTextures[i];
  65699. this._textures.push(texture);
  65700. }
  65701. // Keeps references to frame buffer and stencil/depth buffer
  65702. this._texture = this._internalTextures[0];
  65703. };
  65704. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  65705. get: function () {
  65706. return this._samples;
  65707. },
  65708. set: function (value) {
  65709. if (this._samples === value) {
  65710. return;
  65711. }
  65712. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  65713. },
  65714. enumerable: true,
  65715. configurable: true
  65716. });
  65717. MultiRenderTarget.prototype.resize = function (size) {
  65718. this.releaseInternalTextures();
  65719. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  65720. this._createInternalTextures();
  65721. };
  65722. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65723. var _this = this;
  65724. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  65725. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65726. });
  65727. };
  65728. MultiRenderTarget.prototype.dispose = function () {
  65729. this.releaseInternalTextures();
  65730. _super.prototype.dispose.call(this);
  65731. };
  65732. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  65733. if (!this._internalTextures) {
  65734. return;
  65735. }
  65736. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  65737. if (this._internalTextures[i] !== undefined) {
  65738. this._internalTextures[i].dispose();
  65739. this._internalTextures.splice(i, 1);
  65740. }
  65741. }
  65742. };
  65743. return MultiRenderTarget;
  65744. }(BABYLON.RenderTargetTexture));
  65745. BABYLON.MultiRenderTarget = MultiRenderTarget;
  65746. })(BABYLON || (BABYLON = {}));
  65747. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  65748. var BABYLON;
  65749. (function (BABYLON) {
  65750. var MirrorTexture = /** @class */ (function (_super) {
  65751. __extends(MirrorTexture, _super);
  65752. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  65753. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65754. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65755. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  65756. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  65757. _this.scene = scene;
  65758. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  65759. _this._transformMatrix = BABYLON.Matrix.Zero();
  65760. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  65761. _this._adaptiveBlurKernel = 0;
  65762. _this._blurKernelX = 0;
  65763. _this._blurKernelY = 0;
  65764. _this._blurRatio = 1.0;
  65765. _this.ignoreCameraViewport = true;
  65766. _this._updateGammaSpace();
  65767. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  65768. _this._updateGammaSpace;
  65769. });
  65770. _this.onBeforeRenderObservable.add(function () {
  65771. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  65772. _this._savedViewMatrix = scene.getViewMatrix();
  65773. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  65774. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  65775. scene.clipPlane = _this.mirrorPlane;
  65776. scene.getEngine().cullBackFaces = false;
  65777. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  65778. });
  65779. _this.onAfterRenderObservable.add(function () {
  65780. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  65781. scene.getEngine().cullBackFaces = true;
  65782. scene._mirroredCameraPosition = null;
  65783. delete scene.clipPlane;
  65784. });
  65785. return _this;
  65786. }
  65787. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  65788. get: function () {
  65789. return this._blurRatio;
  65790. },
  65791. set: function (value) {
  65792. if (this._blurRatio === value) {
  65793. return;
  65794. }
  65795. this._blurRatio = value;
  65796. this._preparePostProcesses();
  65797. },
  65798. enumerable: true,
  65799. configurable: true
  65800. });
  65801. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  65802. set: function (value) {
  65803. this._adaptiveBlurKernel = value;
  65804. this._autoComputeBlurKernel();
  65805. },
  65806. enumerable: true,
  65807. configurable: true
  65808. });
  65809. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  65810. set: function (value) {
  65811. this.blurKernelX = value;
  65812. this.blurKernelY = value;
  65813. },
  65814. enumerable: true,
  65815. configurable: true
  65816. });
  65817. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  65818. get: function () {
  65819. return this._blurKernelX;
  65820. },
  65821. set: function (value) {
  65822. if (this._blurKernelX === value) {
  65823. return;
  65824. }
  65825. this._blurKernelX = value;
  65826. this._preparePostProcesses();
  65827. },
  65828. enumerable: true,
  65829. configurable: true
  65830. });
  65831. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  65832. get: function () {
  65833. return this._blurKernelY;
  65834. },
  65835. set: function (value) {
  65836. if (this._blurKernelY === value) {
  65837. return;
  65838. }
  65839. this._blurKernelY = value;
  65840. this._preparePostProcesses();
  65841. },
  65842. enumerable: true,
  65843. configurable: true
  65844. });
  65845. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  65846. var engine = this.getScene().getEngine();
  65847. var dw = this.getRenderWidth() / engine.getRenderWidth();
  65848. var dh = this.getRenderHeight() / engine.getRenderHeight();
  65849. this.blurKernelX = this._adaptiveBlurKernel * dw;
  65850. this.blurKernelY = this._adaptiveBlurKernel * dh;
  65851. };
  65852. MirrorTexture.prototype._onRatioRescale = function () {
  65853. if (this._sizeRatio) {
  65854. this.resize(this._initialSizeParameter);
  65855. if (!this._adaptiveBlurKernel) {
  65856. this._preparePostProcesses();
  65857. }
  65858. }
  65859. if (this._adaptiveBlurKernel) {
  65860. this._autoComputeBlurKernel();
  65861. }
  65862. };
  65863. MirrorTexture.prototype._updateGammaSpace = function () {
  65864. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  65865. };
  65866. MirrorTexture.prototype._preparePostProcesses = function () {
  65867. this.clearPostProcesses(true);
  65868. if (this._blurKernelX && this._blurKernelY) {
  65869. var engine = this.getScene().getEngine();
  65870. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65871. 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);
  65872. this._blurX.autoClear = false;
  65873. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  65874. this._blurX.inputTexture = this._texture;
  65875. }
  65876. else {
  65877. this._blurX.alwaysForcePOT = true;
  65878. }
  65879. 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);
  65880. this._blurY.autoClear = false;
  65881. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  65882. this.addPostProcess(this._blurX);
  65883. this.addPostProcess(this._blurY);
  65884. }
  65885. else {
  65886. if (this._blurY) {
  65887. this.removePostProcess(this._blurY);
  65888. this._blurY.dispose();
  65889. this._blurY = null;
  65890. }
  65891. if (this._blurX) {
  65892. this.removePostProcess(this._blurX);
  65893. this._blurX.dispose();
  65894. this._blurX = null;
  65895. }
  65896. }
  65897. };
  65898. MirrorTexture.prototype.clone = function () {
  65899. var scene = this.getScene();
  65900. if (!scene) {
  65901. return this;
  65902. }
  65903. var textureSize = this.getSize();
  65904. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  65905. // Base texture
  65906. newTexture.hasAlpha = this.hasAlpha;
  65907. newTexture.level = this.level;
  65908. // Mirror Texture
  65909. newTexture.mirrorPlane = this.mirrorPlane.clone();
  65910. if (this.renderList) {
  65911. newTexture.renderList = this.renderList.slice(0);
  65912. }
  65913. return newTexture;
  65914. };
  65915. MirrorTexture.prototype.serialize = function () {
  65916. if (!this.name) {
  65917. return null;
  65918. }
  65919. var serializationObject = _super.prototype.serialize.call(this);
  65920. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  65921. return serializationObject;
  65922. };
  65923. MirrorTexture.prototype.dispose = function () {
  65924. _super.prototype.dispose.call(this);
  65925. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  65926. };
  65927. return MirrorTexture;
  65928. }(BABYLON.RenderTargetTexture));
  65929. BABYLON.MirrorTexture = MirrorTexture;
  65930. })(BABYLON || (BABYLON = {}));
  65931. //# sourceMappingURL=babylon.mirrorTexture.js.map
  65932. var BABYLON;
  65933. (function (BABYLON) {
  65934. /**
  65935. * Creates a refraction texture used by refraction channel of the standard material.
  65936. * @param name the texture name
  65937. * @param size size of the underlying texture
  65938. * @param scene root scene
  65939. */
  65940. var RefractionTexture = /** @class */ (function (_super) {
  65941. __extends(RefractionTexture, _super);
  65942. function RefractionTexture(name, size, scene, generateMipMaps) {
  65943. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  65944. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  65945. _this.depth = 2.0;
  65946. _this.onBeforeRenderObservable.add(function () {
  65947. scene.clipPlane = _this.refractionPlane;
  65948. });
  65949. _this.onAfterRenderObservable.add(function () {
  65950. delete scene.clipPlane;
  65951. });
  65952. return _this;
  65953. }
  65954. RefractionTexture.prototype.clone = function () {
  65955. var scene = this.getScene();
  65956. if (!scene) {
  65957. return this;
  65958. }
  65959. var textureSize = this.getSize();
  65960. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  65961. // Base texture
  65962. newTexture.hasAlpha = this.hasAlpha;
  65963. newTexture.level = this.level;
  65964. // Refraction Texture
  65965. newTexture.refractionPlane = this.refractionPlane.clone();
  65966. if (this.renderList) {
  65967. newTexture.renderList = this.renderList.slice(0);
  65968. }
  65969. newTexture.depth = this.depth;
  65970. return newTexture;
  65971. };
  65972. RefractionTexture.prototype.serialize = function () {
  65973. if (!this.name) {
  65974. return null;
  65975. }
  65976. var serializationObject = _super.prototype.serialize.call(this);
  65977. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  65978. serializationObject.depth = this.depth;
  65979. return serializationObject;
  65980. };
  65981. return RefractionTexture;
  65982. }(BABYLON.RenderTargetTexture));
  65983. BABYLON.RefractionTexture = RefractionTexture;
  65984. })(BABYLON || (BABYLON = {}));
  65985. //# sourceMappingURL=babylon.refractionTexture.js.map
  65986. var BABYLON;
  65987. (function (BABYLON) {
  65988. /**
  65989. * A class extending {BABYLON.Texture} allowing drawing on a texture
  65990. * @see http://doc.babylonjs.com/how_to/dynamictexture
  65991. */
  65992. var DynamicTexture = /** @class */ (function (_super) {
  65993. __extends(DynamicTexture, _super);
  65994. /**
  65995. * Creates a {BABYLON.DynamicTexture}
  65996. * @param name defines the name of the texture
  65997. * @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
  65998. * @param scene defines the scene where you want the texture
  65999. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  66000. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  66001. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  66002. */
  66003. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  66004. if (scene === void 0) { scene = null; }
  66005. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66006. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66007. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  66008. _this.name = name;
  66009. _this._engine = _this.getScene().getEngine();
  66010. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66011. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66012. _this._generateMipMaps = generateMipMaps;
  66013. if (options.getContext) {
  66014. _this._canvas = options;
  66015. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66016. }
  66017. else {
  66018. _this._canvas = document.createElement("canvas");
  66019. if (options.width || options.width === 0) {
  66020. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66021. }
  66022. else {
  66023. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  66024. }
  66025. }
  66026. var textureSize = _this.getSize();
  66027. _this._canvas.width = textureSize.width;
  66028. _this._canvas.height = textureSize.height;
  66029. _this._context = _this._canvas.getContext("2d");
  66030. return _this;
  66031. }
  66032. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  66033. /**
  66034. * Gets the current state of canRescale
  66035. */
  66036. get: function () {
  66037. return true;
  66038. },
  66039. enumerable: true,
  66040. configurable: true
  66041. });
  66042. DynamicTexture.prototype._recreate = function (textureSize) {
  66043. this._canvas.width = textureSize.width;
  66044. this._canvas.height = textureSize.height;
  66045. this.releaseInternalTexture();
  66046. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  66047. };
  66048. /**
  66049. * Scales the texture
  66050. * @param ratio the scale factor to apply to both width and height
  66051. */
  66052. DynamicTexture.prototype.scale = function (ratio) {
  66053. var textureSize = this.getSize();
  66054. textureSize.width *= ratio;
  66055. textureSize.height *= ratio;
  66056. this._recreate(textureSize);
  66057. };
  66058. /**
  66059. * Resizes the texture
  66060. * @param width the new width
  66061. * @param height the new height
  66062. */
  66063. DynamicTexture.prototype.scaleTo = function (width, height) {
  66064. var textureSize = this.getSize();
  66065. textureSize.width = width;
  66066. textureSize.height = height;
  66067. this._recreate(textureSize);
  66068. };
  66069. /**
  66070. * Gets the context of the canvas used by the texture
  66071. * @returns the canvas context of the dynamic texture
  66072. */
  66073. DynamicTexture.prototype.getContext = function () {
  66074. return this._context;
  66075. };
  66076. /**
  66077. * Clears the texture
  66078. */
  66079. DynamicTexture.prototype.clear = function () {
  66080. var size = this.getSize();
  66081. this._context.fillRect(0, 0, size.width, size.height);
  66082. };
  66083. /**
  66084. * Updates the texture
  66085. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66086. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  66087. */
  66088. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  66089. if (premulAlpha === void 0) { premulAlpha = false; }
  66090. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  66091. };
  66092. /**
  66093. * Draws text onto the texture
  66094. * @param text defines the text to be drawn
  66095. * @param x defines the placement of the text from the left
  66096. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  66097. * @param font defines the font to be used with font-style, font-size, font-name
  66098. * @param color defines the color used for the text
  66099. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  66100. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66101. * @param update defines whether texture is immediately update (default is true)
  66102. */
  66103. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  66104. if (update === void 0) { update = true; }
  66105. var size = this.getSize();
  66106. if (clearColor) {
  66107. this._context.fillStyle = clearColor;
  66108. this._context.fillRect(0, 0, size.width, size.height);
  66109. }
  66110. this._context.font = font;
  66111. if (x === null || x === undefined) {
  66112. var textSize = this._context.measureText(text);
  66113. x = (size.width - textSize.width) / 2;
  66114. }
  66115. if (y === null || y === undefined) {
  66116. var fontSize = parseInt((font.replace(/\D/g, '')));
  66117. y = (size.height / 2) + (fontSize / 3.65);
  66118. }
  66119. this._context.fillStyle = color;
  66120. this._context.fillText(text, x, y);
  66121. if (update) {
  66122. this.update(invertY);
  66123. }
  66124. };
  66125. /**
  66126. * Clones the texture
  66127. * @returns the clone of the texture.
  66128. */
  66129. DynamicTexture.prototype.clone = function () {
  66130. var scene = this.getScene();
  66131. if (!scene) {
  66132. return this;
  66133. }
  66134. var textureSize = this.getSize();
  66135. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  66136. // Base texture
  66137. newTexture.hasAlpha = this.hasAlpha;
  66138. newTexture.level = this.level;
  66139. // Dynamic Texture
  66140. newTexture.wrapU = this.wrapU;
  66141. newTexture.wrapV = this.wrapV;
  66142. return newTexture;
  66143. };
  66144. /** @hidden */
  66145. DynamicTexture.prototype._rebuild = function () {
  66146. this.update();
  66147. };
  66148. return DynamicTexture;
  66149. }(BABYLON.Texture));
  66150. BABYLON.DynamicTexture = DynamicTexture;
  66151. })(BABYLON || (BABYLON = {}));
  66152. //# sourceMappingURL=babylon.dynamicTexture.js.map
  66153. var BABYLON;
  66154. (function (BABYLON) {
  66155. var VideoTexture = /** @class */ (function (_super) {
  66156. __extends(VideoTexture, _super);
  66157. /**
  66158. * Creates a video texture.
  66159. * Sample : https://doc.babylonjs.com/how_to/video_texture
  66160. * @param {string | null} name optional name, will detect from video source, if not defined
  66161. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  66162. * @param {BABYLON.Scene} scene is obviously the current scene.
  66163. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  66164. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  66165. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  66166. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  66167. */
  66168. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  66169. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66170. if (invertY === void 0) { invertY = false; }
  66171. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66172. if (settings === void 0) { settings = {
  66173. autoPlay: true,
  66174. loop: true,
  66175. autoUpdateTexture: true,
  66176. }; }
  66177. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66178. _this._onUserActionRequestedObservable = null;
  66179. _this._stillImageCaptured = false;
  66180. _this._poster = false;
  66181. _this._createInternalTexture = function () {
  66182. if (_this._texture != null) {
  66183. if (_this._poster) {
  66184. _this._texture.dispose();
  66185. _this._poster = false;
  66186. }
  66187. else {
  66188. return;
  66189. }
  66190. }
  66191. if (!_this._engine.needPOTTextures ||
  66192. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  66193. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66194. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66195. }
  66196. else {
  66197. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66198. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66199. _this._generateMipMaps = false;
  66200. }
  66201. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  66202. if (!_this.video.autoplay) {
  66203. var oldHandler_1 = _this.video.onplaying;
  66204. var error_1 = false;
  66205. _this.video.onplaying = function () {
  66206. _this.video.onplaying = oldHandler_1;
  66207. _this._texture.isReady = true;
  66208. _this._updateInternalTexture();
  66209. if (!error_1) {
  66210. _this.video.pause();
  66211. }
  66212. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66213. _this.onLoadObservable.notifyObservers(_this);
  66214. }
  66215. };
  66216. var playing = _this.video.play();
  66217. if (playing) {
  66218. playing.then(function () {
  66219. // Everything is good.
  66220. })
  66221. .catch(function () {
  66222. error_1 = true;
  66223. // On Chrome for instance, new policies might prevent playing without user interaction.
  66224. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  66225. _this._onUserActionRequestedObservable.notifyObservers(_this);
  66226. }
  66227. });
  66228. }
  66229. else {
  66230. _this.video.onplaying = oldHandler_1;
  66231. _this._texture.isReady = true;
  66232. _this._updateInternalTexture();
  66233. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66234. _this.onLoadObservable.notifyObservers(_this);
  66235. }
  66236. }
  66237. }
  66238. else {
  66239. _this._texture.isReady = true;
  66240. _this._updateInternalTexture();
  66241. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66242. _this.onLoadObservable.notifyObservers(_this);
  66243. }
  66244. }
  66245. };
  66246. _this.reset = function () {
  66247. if (_this._texture == null) {
  66248. return;
  66249. }
  66250. if (!_this._poster) {
  66251. _this._texture.dispose();
  66252. _this._texture = null;
  66253. }
  66254. };
  66255. _this._updateInternalTexture = function (e) {
  66256. if (_this._texture == null || !_this._texture.isReady) {
  66257. return;
  66258. }
  66259. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  66260. return;
  66261. }
  66262. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  66263. };
  66264. _this._engine = _this.getScene().getEngine();
  66265. _this._generateMipMaps = generateMipMaps;
  66266. _this._samplingMode = samplingMode;
  66267. _this.autoUpdateTexture = settings.autoUpdateTexture;
  66268. _this.name = name || _this._getName(src);
  66269. _this.video = _this._getVideo(src);
  66270. if (settings.poster) {
  66271. _this.video.poster = settings.poster;
  66272. }
  66273. if (settings.autoPlay !== undefined) {
  66274. _this.video.autoplay = settings.autoPlay;
  66275. }
  66276. if (settings.loop !== undefined) {
  66277. _this.video.loop = settings.loop;
  66278. }
  66279. _this.video.setAttribute("playsinline", "");
  66280. _this.video.addEventListener("canplay", _this._createInternalTexture);
  66281. _this.video.addEventListener("paused", _this._updateInternalTexture);
  66282. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  66283. _this.video.addEventListener("emptied", _this.reset);
  66284. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  66285. _this._createInternalTexture();
  66286. }
  66287. if (settings.poster) {
  66288. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  66289. _this._poster = true;
  66290. }
  66291. return _this;
  66292. }
  66293. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  66294. get: function () {
  66295. if (!this._onUserActionRequestedObservable) {
  66296. this._onUserActionRequestedObservable = new BABYLON.Observable();
  66297. }
  66298. return this._onUserActionRequestedObservable;
  66299. },
  66300. enumerable: true,
  66301. configurable: true
  66302. });
  66303. VideoTexture.prototype._getName = function (src) {
  66304. if (src instanceof HTMLVideoElement) {
  66305. return src.currentSrc;
  66306. }
  66307. if (typeof src === "object") {
  66308. return src.toString();
  66309. }
  66310. return src;
  66311. };
  66312. ;
  66313. VideoTexture.prototype._getVideo = function (src) {
  66314. if (src instanceof HTMLVideoElement) {
  66315. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  66316. return src;
  66317. }
  66318. var video = document.createElement("video");
  66319. if (typeof src === "string") {
  66320. BABYLON.Tools.SetCorsBehavior(src, video);
  66321. video.src = src;
  66322. }
  66323. else {
  66324. BABYLON.Tools.SetCorsBehavior(src[0], video);
  66325. src.forEach(function (url) {
  66326. var source = document.createElement("source");
  66327. source.src = url;
  66328. video.appendChild(source);
  66329. });
  66330. }
  66331. return video;
  66332. };
  66333. ;
  66334. /**
  66335. * Internal method to initiate `update`.
  66336. */
  66337. VideoTexture.prototype._rebuild = function () {
  66338. this.update();
  66339. };
  66340. /**
  66341. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  66342. */
  66343. VideoTexture.prototype.update = function () {
  66344. if (!this.autoUpdateTexture) {
  66345. // Expecting user to call `updateTexture` manually
  66346. return;
  66347. }
  66348. this.updateTexture(true);
  66349. };
  66350. /**
  66351. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  66352. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  66353. */
  66354. VideoTexture.prototype.updateTexture = function (isVisible) {
  66355. if (!isVisible) {
  66356. return;
  66357. }
  66358. if (this.video.paused && this._stillImageCaptured) {
  66359. return;
  66360. }
  66361. this._stillImageCaptured = true;
  66362. this._updateInternalTexture();
  66363. };
  66364. /**
  66365. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  66366. * @param url New url.
  66367. */
  66368. VideoTexture.prototype.updateURL = function (url) {
  66369. this.video.src = url;
  66370. };
  66371. VideoTexture.prototype.dispose = function () {
  66372. _super.prototype.dispose.call(this);
  66373. if (this._onUserActionRequestedObservable) {
  66374. this._onUserActionRequestedObservable.clear();
  66375. this._onUserActionRequestedObservable = null;
  66376. }
  66377. this.video.removeEventListener("canplay", this._createInternalTexture);
  66378. this.video.removeEventListener("paused", this._updateInternalTexture);
  66379. this.video.removeEventListener("seeked", this._updateInternalTexture);
  66380. this.video.removeEventListener("emptied", this.reset);
  66381. this.video.pause();
  66382. };
  66383. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  66384. var video = document.createElement("video");
  66385. video.setAttribute('autoplay', '');
  66386. video.setAttribute('muted', '');
  66387. video.setAttribute('playsinline', '');
  66388. var constraintsDeviceId;
  66389. if (constraints && constraints.deviceId) {
  66390. constraintsDeviceId = {
  66391. exact: constraints.deviceId,
  66392. };
  66393. }
  66394. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  66395. if (navigator.mediaDevices) {
  66396. navigator.mediaDevices.getUserMedia({ video: constraints })
  66397. .then(function (stream) {
  66398. if (video.mozSrcObject !== undefined) {
  66399. // hack for Firefox < 19
  66400. video.mozSrcObject = stream;
  66401. }
  66402. else {
  66403. video.srcObject = stream;
  66404. }
  66405. var onPlaying = function () {
  66406. if (onReady) {
  66407. onReady(new VideoTexture("video", video, scene, true, true));
  66408. }
  66409. video.removeEventListener("playing", onPlaying);
  66410. };
  66411. video.addEventListener("playing", onPlaying);
  66412. video.play();
  66413. })
  66414. .catch(function (err) {
  66415. BABYLON.Tools.Error(err.name);
  66416. });
  66417. }
  66418. else {
  66419. navigator.getUserMedia =
  66420. navigator.getUserMedia ||
  66421. navigator.webkitGetUserMedia ||
  66422. navigator.mozGetUserMedia ||
  66423. navigator.msGetUserMedia;
  66424. if (navigator.getUserMedia) {
  66425. navigator.getUserMedia({
  66426. video: {
  66427. deviceId: constraintsDeviceId,
  66428. width: {
  66429. min: (constraints && constraints.minWidth) || 256,
  66430. max: (constraints && constraints.maxWidth) || 640,
  66431. },
  66432. height: {
  66433. min: (constraints && constraints.minHeight) || 256,
  66434. max: (constraints && constraints.maxHeight) || 480,
  66435. },
  66436. },
  66437. }, function (stream) {
  66438. if (video.mozSrcObject !== undefined) {
  66439. // hack for Firefox < 19
  66440. video.mozSrcObject = stream;
  66441. }
  66442. else {
  66443. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  66444. }
  66445. video.play();
  66446. if (onReady) {
  66447. onReady(new VideoTexture("video", video, scene, true, true));
  66448. }
  66449. }, function (e) {
  66450. BABYLON.Tools.Error(e.name);
  66451. });
  66452. }
  66453. }
  66454. };
  66455. return VideoTexture;
  66456. }(BABYLON.Texture));
  66457. BABYLON.VideoTexture = VideoTexture;
  66458. })(BABYLON || (BABYLON = {}));
  66459. //# sourceMappingURL=babylon.videoTexture.js.map
  66460. var BABYLON;
  66461. (function (BABYLON) {
  66462. var RawTexture = /** @class */ (function (_super) {
  66463. __extends(RawTexture, _super);
  66464. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  66465. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66466. if (invertY === void 0) { invertY = false; }
  66467. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66468. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66469. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66470. _this.format = format;
  66471. _this._engine = scene.getEngine();
  66472. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  66473. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66474. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66475. return _this;
  66476. }
  66477. RawTexture.prototype.update = function (data) {
  66478. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66479. };
  66480. // Statics
  66481. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66482. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66483. if (invertY === void 0) { invertY = false; }
  66484. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66485. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  66486. };
  66487. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66488. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66489. if (invertY === void 0) { invertY = false; }
  66490. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66491. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66492. };
  66493. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66494. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66495. if (invertY === void 0) { invertY = false; }
  66496. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66497. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66498. };
  66499. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66500. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66501. if (invertY === void 0) { invertY = false; }
  66502. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66503. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66504. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  66505. };
  66506. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66507. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66508. if (invertY === void 0) { invertY = false; }
  66509. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66510. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66511. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  66512. };
  66513. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66514. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66515. if (invertY === void 0) { invertY = false; }
  66516. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66517. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66518. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  66519. };
  66520. return RawTexture;
  66521. }(BABYLON.Texture));
  66522. BABYLON.RawTexture = RawTexture;
  66523. })(BABYLON || (BABYLON = {}));
  66524. //# sourceMappingURL=babylon.rawTexture.js.map
  66525. var BABYLON;
  66526. (function (BABYLON) {
  66527. /**
  66528. * Class used to store 3D textures containing user data
  66529. */
  66530. var RawTexture3D = /** @class */ (function (_super) {
  66531. __extends(RawTexture3D, _super);
  66532. /**
  66533. * Create a new RawTexture3D
  66534. * @param data defines the data of the texture
  66535. * @param width defines the width of the texture
  66536. * @param height defines the height of the texture
  66537. * @param depth defines the depth of the texture
  66538. * @param format defines the texture format to use
  66539. * @param scene defines the hosting scene
  66540. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  66541. * @param invertY defines if texture must be stored with Y axis inverted
  66542. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  66543. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  66544. */
  66545. function RawTexture3D(data, width, height, depth,
  66546. /** Gets or sets the texture format to use */
  66547. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  66548. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66549. if (invertY === void 0) { invertY = false; }
  66550. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66551. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66552. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66553. _this.format = format;
  66554. _this._engine = scene.getEngine();
  66555. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  66556. _this.is3D = true;
  66557. return _this;
  66558. }
  66559. /**
  66560. * Update the texture with new data
  66561. * @param data defines the data to store in the texture
  66562. */
  66563. RawTexture3D.prototype.update = function (data) {
  66564. if (!this._texture) {
  66565. return;
  66566. }
  66567. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66568. };
  66569. return RawTexture3D;
  66570. }(BABYLON.Texture));
  66571. BABYLON.RawTexture3D = RawTexture3D;
  66572. })(BABYLON || (BABYLON = {}));
  66573. //# sourceMappingURL=babylon.rawTexture3D.js.map
  66574. var BABYLON;
  66575. (function (BABYLON) {
  66576. /**
  66577. * PostProcessManager is used to manage one or more post processes or post process pipelines
  66578. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66579. */
  66580. var PostProcessManager = /** @class */ (function () {
  66581. /**
  66582. * Creates a new instance PostProcess
  66583. * @param scene The scene that the post process is associated with.
  66584. */
  66585. function PostProcessManager(scene) {
  66586. this._vertexBuffers = {};
  66587. this._scene = scene;
  66588. }
  66589. PostProcessManager.prototype._prepareBuffers = function () {
  66590. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  66591. return;
  66592. }
  66593. // VBO
  66594. var vertices = [];
  66595. vertices.push(1, 1);
  66596. vertices.push(-1, 1);
  66597. vertices.push(-1, -1);
  66598. vertices.push(1, -1);
  66599. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66600. this._buildIndexBuffer();
  66601. };
  66602. PostProcessManager.prototype._buildIndexBuffer = function () {
  66603. // Indices
  66604. var indices = [];
  66605. indices.push(0);
  66606. indices.push(1);
  66607. indices.push(2);
  66608. indices.push(0);
  66609. indices.push(2);
  66610. indices.push(3);
  66611. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  66612. };
  66613. /**
  66614. * Rebuilds the vertex buffers of the manager.
  66615. */
  66616. PostProcessManager.prototype._rebuild = function () {
  66617. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66618. if (!vb) {
  66619. return;
  66620. }
  66621. vb._rebuild();
  66622. this._buildIndexBuffer();
  66623. };
  66624. // Methods
  66625. /**
  66626. * Prepares a frame to be run through a post process.
  66627. * @param sourceTexture The input texture to the post procesess. (default: null)
  66628. * @param postProcesses An array of post processes to be run. (default: null)
  66629. * @returns True if the post processes were able to be run.
  66630. */
  66631. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  66632. if (sourceTexture === void 0) { sourceTexture = null; }
  66633. if (postProcesses === void 0) { postProcesses = null; }
  66634. var camera = this._scene.activeCamera;
  66635. if (!camera) {
  66636. return false;
  66637. }
  66638. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66639. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66640. return false;
  66641. }
  66642. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  66643. return true;
  66644. };
  66645. /**
  66646. * Manually render a set of post processes to a texture.
  66647. * @param postProcesses An array of post processes to be run.
  66648. * @param targetTexture The target texture to render to.
  66649. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  66650. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  66651. * @param lodLevel defines which lod of the texture to render to
  66652. */
  66653. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  66654. if (targetTexture === void 0) { targetTexture = null; }
  66655. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66656. if (faceIndex === void 0) { faceIndex = 0; }
  66657. if (lodLevel === void 0) { lodLevel = 0; }
  66658. var engine = this._scene.getEngine();
  66659. for (var index = 0; index < postProcesses.length; index++) {
  66660. if (index < postProcesses.length - 1) {
  66661. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  66662. }
  66663. else {
  66664. if (targetTexture) {
  66665. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  66666. }
  66667. else {
  66668. engine.restoreDefaultFramebuffer();
  66669. }
  66670. }
  66671. var pp = postProcesses[index];
  66672. var effect = pp.apply();
  66673. if (effect) {
  66674. pp.onBeforeRenderObservable.notifyObservers(effect);
  66675. // VBOs
  66676. this._prepareBuffers();
  66677. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66678. // Draw order
  66679. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66680. pp.onAfterRenderObservable.notifyObservers(effect);
  66681. }
  66682. }
  66683. // Restore depth buffer
  66684. engine.setDepthBuffer(true);
  66685. engine.setDepthWrite(true);
  66686. };
  66687. /**
  66688. * Finalize the result of the output of the postprocesses.
  66689. * @param doNotPresent If true the result will not be displayed to the screen.
  66690. * @param targetTexture The target texture to render to.
  66691. * @param faceIndex The index of the face to bind the target texture to.
  66692. * @param postProcesses The array of post processes to render.
  66693. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  66694. */
  66695. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  66696. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66697. var camera = this._scene.activeCamera;
  66698. if (!camera) {
  66699. return;
  66700. }
  66701. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66702. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66703. return;
  66704. }
  66705. var engine = this._scene.getEngine();
  66706. for (var index = 0, len = postProcesses.length; index < len; index++) {
  66707. var pp = postProcesses[index];
  66708. if (index < len - 1) {
  66709. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  66710. }
  66711. else {
  66712. if (targetTexture) {
  66713. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  66714. pp._outputTexture = targetTexture;
  66715. }
  66716. else {
  66717. engine.restoreDefaultFramebuffer();
  66718. pp._outputTexture = null;
  66719. }
  66720. }
  66721. if (doNotPresent) {
  66722. break;
  66723. }
  66724. var effect = pp.apply();
  66725. if (effect) {
  66726. pp.onBeforeRenderObservable.notifyObservers(effect);
  66727. // VBOs
  66728. this._prepareBuffers();
  66729. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66730. // Draw order
  66731. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66732. pp.onAfterRenderObservable.notifyObservers(effect);
  66733. }
  66734. }
  66735. // Restore states
  66736. engine.setDepthBuffer(true);
  66737. engine.setDepthWrite(true);
  66738. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66739. };
  66740. /**
  66741. * Disposes of the post process manager.
  66742. */
  66743. PostProcessManager.prototype.dispose = function () {
  66744. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66745. if (buffer) {
  66746. buffer.dispose();
  66747. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66748. }
  66749. if (this._indexBuffer) {
  66750. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66751. this._indexBuffer = null;
  66752. }
  66753. };
  66754. return PostProcessManager;
  66755. }());
  66756. BABYLON.PostProcessManager = PostProcessManager;
  66757. })(BABYLON || (BABYLON = {}));
  66758. //# sourceMappingURL=babylon.postProcessManager.js.map
  66759. var BABYLON;
  66760. (function (BABYLON) {
  66761. /**
  66762. * PostProcess can be used to apply a shader to a texture after it has been rendered
  66763. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66764. */
  66765. var PostProcess = /** @class */ (function () {
  66766. /**
  66767. * Creates a new instance PostProcess
  66768. * @param name The name of the PostProcess.
  66769. * @param fragmentUrl The url of the fragment shader to be used.
  66770. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  66771. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  66772. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  66773. * @param camera The camera to apply the render pass to.
  66774. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66775. * @param engine The engine which the post process will be applied. (default: current engine)
  66776. * @param reusable If the post process can be reused on the same frame. (default: false)
  66777. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  66778. * @param textureType Type of textures used when performing the post process. (default: 0)
  66779. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  66780. * @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
  66781. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  66782. */
  66783. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  66784. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  66785. if (defines === void 0) { defines = null; }
  66786. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66787. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  66788. if (blockCompilation === void 0) { blockCompilation = false; }
  66789. this.name = name;
  66790. /**
  66791. * Width of the texture to apply the post process on
  66792. */
  66793. this.width = -1;
  66794. /**
  66795. * Height of the texture to apply the post process on
  66796. */
  66797. this.height = -1;
  66798. /**
  66799. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  66800. */
  66801. this._outputTexture = null;
  66802. /**
  66803. * If the buffer needs to be cleared before applying the post process. (default: true)
  66804. * Should be set to false if shader will overwrite all previous pixels.
  66805. */
  66806. this.autoClear = true;
  66807. /**
  66808. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  66809. */
  66810. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  66811. /**
  66812. * Animations to be used for the post processing
  66813. */
  66814. this.animations = new Array();
  66815. /**
  66816. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  66817. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  66818. */
  66819. this.enablePixelPerfectMode = false;
  66820. /**
  66821. * Force the postprocess to be applied without taking in account viewport
  66822. */
  66823. this.forceFullscreenViewport = true;
  66824. /**
  66825. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  66826. *
  66827. * | Value | Type | Description |
  66828. * | ----- | ----------------------------------- | ----------- |
  66829. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  66830. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  66831. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  66832. *
  66833. */
  66834. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  66835. /**
  66836. * Force textures to be a power of two (default: false)
  66837. */
  66838. this.alwaysForcePOT = false;
  66839. /**
  66840. * Number of sample textures (default: 1)
  66841. */
  66842. this.samples = 1;
  66843. /**
  66844. * Modify the scale of the post process to be the same as the viewport (default: false)
  66845. */
  66846. this.adaptScaleToCurrentViewport = false;
  66847. this._reusable = false;
  66848. /**
  66849. * Smart array of input and output textures for the post process.
  66850. */
  66851. this._textures = new BABYLON.SmartArray(2);
  66852. /**
  66853. * The index in _textures that corresponds to the output texture.
  66854. */
  66855. this._currentRenderTextureInd = 0;
  66856. this._scaleRatio = new BABYLON.Vector2(1, 1);
  66857. this._texelSize = BABYLON.Vector2.Zero();
  66858. // Events
  66859. /**
  66860. * An event triggered when the postprocess is activated.
  66861. */
  66862. this.onActivateObservable = new BABYLON.Observable();
  66863. /**
  66864. * An event triggered when the postprocess changes its size.
  66865. */
  66866. this.onSizeChangedObservable = new BABYLON.Observable();
  66867. /**
  66868. * An event triggered when the postprocess applies its effect.
  66869. */
  66870. this.onApplyObservable = new BABYLON.Observable();
  66871. /**
  66872. * An event triggered before rendering the postprocess
  66873. */
  66874. this.onBeforeRenderObservable = new BABYLON.Observable();
  66875. /**
  66876. * An event triggered after rendering the postprocess
  66877. */
  66878. this.onAfterRenderObservable = new BABYLON.Observable();
  66879. if (camera != null) {
  66880. this._camera = camera;
  66881. this._scene = camera.getScene();
  66882. camera.attachPostProcess(this);
  66883. this._engine = this._scene.getEngine();
  66884. this._scene.postProcesses.push(this);
  66885. }
  66886. else if (engine) {
  66887. this._engine = engine;
  66888. this._engine.postProcesses.push(this);
  66889. }
  66890. this._options = options;
  66891. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  66892. this._reusable = reusable || false;
  66893. this._textureType = textureType;
  66894. this._samplers = samplers || [];
  66895. this._samplers.push("textureSampler");
  66896. this._fragmentUrl = fragmentUrl;
  66897. this._vertexUrl = vertexUrl;
  66898. this._parameters = parameters || [];
  66899. this._parameters.push("scale");
  66900. this._indexParameters = indexParameters;
  66901. if (!blockCompilation) {
  66902. this.updateEffect(defines);
  66903. }
  66904. }
  66905. Object.defineProperty(PostProcess.prototype, "onActivate", {
  66906. /**
  66907. * A function that is added to the onActivateObservable
  66908. */
  66909. set: function (callback) {
  66910. if (this._onActivateObserver) {
  66911. this.onActivateObservable.remove(this._onActivateObserver);
  66912. }
  66913. if (callback) {
  66914. this._onActivateObserver = this.onActivateObservable.add(callback);
  66915. }
  66916. },
  66917. enumerable: true,
  66918. configurable: true
  66919. });
  66920. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  66921. /**
  66922. * A function that is added to the onSizeChangedObservable
  66923. */
  66924. set: function (callback) {
  66925. if (this._onSizeChangedObserver) {
  66926. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  66927. }
  66928. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  66929. },
  66930. enumerable: true,
  66931. configurable: true
  66932. });
  66933. Object.defineProperty(PostProcess.prototype, "onApply", {
  66934. /**
  66935. * A function that is added to the onApplyObservable
  66936. */
  66937. set: function (callback) {
  66938. if (this._onApplyObserver) {
  66939. this.onApplyObservable.remove(this._onApplyObserver);
  66940. }
  66941. this._onApplyObserver = this.onApplyObservable.add(callback);
  66942. },
  66943. enumerable: true,
  66944. configurable: true
  66945. });
  66946. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  66947. /**
  66948. * A function that is added to the onBeforeRenderObservable
  66949. */
  66950. set: function (callback) {
  66951. if (this._onBeforeRenderObserver) {
  66952. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  66953. }
  66954. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  66955. },
  66956. enumerable: true,
  66957. configurable: true
  66958. });
  66959. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  66960. /**
  66961. * A function that is added to the onAfterRenderObservable
  66962. */
  66963. set: function (callback) {
  66964. if (this._onAfterRenderObserver) {
  66965. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  66966. }
  66967. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  66968. },
  66969. enumerable: true,
  66970. configurable: true
  66971. });
  66972. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  66973. /**
  66974. * 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
  66975. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  66976. */
  66977. get: function () {
  66978. return this._textures.data[this._currentRenderTextureInd];
  66979. },
  66980. set: function (value) {
  66981. this._forcedOutputTexture = value;
  66982. },
  66983. enumerable: true,
  66984. configurable: true
  66985. });
  66986. /**
  66987. * Gets the camera which post process is applied to.
  66988. * @returns The camera the post process is applied to.
  66989. */
  66990. PostProcess.prototype.getCamera = function () {
  66991. return this._camera;
  66992. };
  66993. Object.defineProperty(PostProcess.prototype, "texelSize", {
  66994. /**
  66995. * Gets the texel size of the postprocess.
  66996. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  66997. */
  66998. get: function () {
  66999. if (this._shareOutputWithPostProcess) {
  67000. return this._shareOutputWithPostProcess.texelSize;
  67001. }
  67002. if (this._forcedOutputTexture) {
  67003. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  67004. }
  67005. return this._texelSize;
  67006. },
  67007. enumerable: true,
  67008. configurable: true
  67009. });
  67010. /**
  67011. * Gets the engine which this post process belongs to.
  67012. * @returns The engine the post process was enabled with.
  67013. */
  67014. PostProcess.prototype.getEngine = function () {
  67015. return this._engine;
  67016. };
  67017. /**
  67018. * The effect that is created when initializing the post process.
  67019. * @returns The created effect corrisponding the the postprocess.
  67020. */
  67021. PostProcess.prototype.getEffect = function () {
  67022. return this._effect;
  67023. };
  67024. /**
  67025. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  67026. * @param postProcess The post process to share the output with.
  67027. * @returns This post process.
  67028. */
  67029. PostProcess.prototype.shareOutputWith = function (postProcess) {
  67030. this._disposeTextures();
  67031. this._shareOutputWithPostProcess = postProcess;
  67032. return this;
  67033. };
  67034. /**
  67035. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  67036. * This should be called if the post process that shares output with this post process is disabled/disposed.
  67037. */
  67038. PostProcess.prototype.useOwnOutput = function () {
  67039. if (this._textures.length == 0) {
  67040. this._textures = new BABYLON.SmartArray(2);
  67041. }
  67042. this._shareOutputWithPostProcess = null;
  67043. };
  67044. /**
  67045. * Updates the effect with the current post process compile time values and recompiles the shader.
  67046. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  67047. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  67048. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  67049. * @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
  67050. * @param onCompiled Called when the shader has been compiled.
  67051. * @param onError Called if there is an error when compiling a shader.
  67052. */
  67053. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  67054. if (defines === void 0) { defines = null; }
  67055. if (uniforms === void 0) { uniforms = null; }
  67056. if (samplers === void 0) { samplers = null; }
  67057. 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);
  67058. };
  67059. /**
  67060. * The post process is reusable if it can be used multiple times within one frame.
  67061. * @returns If the post process is reusable
  67062. */
  67063. PostProcess.prototype.isReusable = function () {
  67064. return this._reusable;
  67065. };
  67066. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  67067. PostProcess.prototype.markTextureDirty = function () {
  67068. this.width = -1;
  67069. };
  67070. /**
  67071. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  67072. * 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.
  67073. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  67074. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  67075. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  67076. * @returns The target texture that was bound to be written to.
  67077. */
  67078. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  67079. var _this = this;
  67080. if (sourceTexture === void 0) { sourceTexture = null; }
  67081. camera = camera || this._camera;
  67082. var scene = camera.getScene();
  67083. var engine = scene.getEngine();
  67084. var maxSize = engine.getCaps().maxTextureSize;
  67085. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  67086. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  67087. // 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
  67088. var webVRCamera = camera.parent;
  67089. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  67090. requiredWidth /= 2;
  67091. }
  67092. var desiredWidth = (this._options.width || requiredWidth);
  67093. var desiredHeight = this._options.height || requiredHeight;
  67094. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  67095. if (this.adaptScaleToCurrentViewport) {
  67096. var currentViewport = engine.currentViewport;
  67097. if (currentViewport) {
  67098. desiredWidth *= currentViewport.width;
  67099. desiredHeight *= currentViewport.height;
  67100. }
  67101. }
  67102. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  67103. if (!this._options.width) {
  67104. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  67105. }
  67106. if (!this._options.height) {
  67107. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  67108. }
  67109. }
  67110. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  67111. if (this._textures.length > 0) {
  67112. for (var i = 0; i < this._textures.length; i++) {
  67113. this._engine._releaseTexture(this._textures.data[i]);
  67114. }
  67115. this._textures.reset();
  67116. }
  67117. this.width = desiredWidth;
  67118. this.height = desiredHeight;
  67119. var textureSize = { width: this.width, height: this.height };
  67120. var textureOptions = {
  67121. generateMipMaps: false,
  67122. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  67123. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  67124. samplingMode: this.renderTargetSamplingMode,
  67125. type: this._textureType
  67126. };
  67127. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67128. if (this._reusable) {
  67129. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67130. }
  67131. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  67132. this.onSizeChangedObservable.notifyObservers(this);
  67133. }
  67134. this._textures.forEach(function (texture) {
  67135. if (texture.samples !== _this.samples) {
  67136. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  67137. }
  67138. });
  67139. }
  67140. var target;
  67141. if (this._shareOutputWithPostProcess) {
  67142. target = this._shareOutputWithPostProcess.inputTexture;
  67143. }
  67144. else if (this._forcedOutputTexture) {
  67145. target = this._forcedOutputTexture;
  67146. this.width = this._forcedOutputTexture.width;
  67147. this.height = this._forcedOutputTexture.height;
  67148. }
  67149. else {
  67150. target = this.inputTexture;
  67151. }
  67152. // Bind the input of this post process to be used as the output of the previous post process.
  67153. if (this.enablePixelPerfectMode) {
  67154. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  67155. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  67156. }
  67157. else {
  67158. this._scaleRatio.copyFromFloats(1, 1);
  67159. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  67160. }
  67161. this.onActivateObservable.notifyObservers(camera);
  67162. // Clear
  67163. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  67164. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  67165. }
  67166. if (this._reusable) {
  67167. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  67168. }
  67169. return target;
  67170. };
  67171. Object.defineProperty(PostProcess.prototype, "isSupported", {
  67172. /**
  67173. * If the post process is supported.
  67174. */
  67175. get: function () {
  67176. return this._effect.isSupported;
  67177. },
  67178. enumerable: true,
  67179. configurable: true
  67180. });
  67181. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  67182. /**
  67183. * The aspect ratio of the output texture.
  67184. */
  67185. get: function () {
  67186. if (this._shareOutputWithPostProcess) {
  67187. return this._shareOutputWithPostProcess.aspectRatio;
  67188. }
  67189. if (this._forcedOutputTexture) {
  67190. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  67191. }
  67192. return this.width / this.height;
  67193. },
  67194. enumerable: true,
  67195. configurable: true
  67196. });
  67197. /**
  67198. * Get a value indicating if the post-process is ready to be used
  67199. * @returns true if the post-process is ready (shader is compiled)
  67200. */
  67201. PostProcess.prototype.isReady = function () {
  67202. return this._effect && this._effect.isReady();
  67203. };
  67204. /**
  67205. * Binds all textures and uniforms to the shader, this will be run on every pass.
  67206. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  67207. */
  67208. PostProcess.prototype.apply = function () {
  67209. // Check
  67210. if (!this._effect || !this._effect.isReady())
  67211. return null;
  67212. // States
  67213. this._engine.enableEffect(this._effect);
  67214. this._engine.setState(false);
  67215. this._engine.setDepthBuffer(false);
  67216. this._engine.setDepthWrite(false);
  67217. // Alpha
  67218. this._engine.setAlphaMode(this.alphaMode);
  67219. if (this.alphaConstants) {
  67220. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  67221. }
  67222. // Bind the output texture of the preivous post process as the input to this post process.
  67223. var source;
  67224. if (this._shareOutputWithPostProcess) {
  67225. source = this._shareOutputWithPostProcess.inputTexture;
  67226. }
  67227. else if (this._forcedOutputTexture) {
  67228. source = this._forcedOutputTexture;
  67229. }
  67230. else {
  67231. source = this.inputTexture;
  67232. }
  67233. this._effect._bindTexture("textureSampler", source);
  67234. // Parameters
  67235. this._effect.setVector2("scale", this._scaleRatio);
  67236. this.onApplyObservable.notifyObservers(this._effect);
  67237. return this._effect;
  67238. };
  67239. PostProcess.prototype._disposeTextures = function () {
  67240. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  67241. return;
  67242. }
  67243. if (this._textures.length > 0) {
  67244. for (var i = 0; i < this._textures.length; i++) {
  67245. this._engine._releaseTexture(this._textures.data[i]);
  67246. }
  67247. }
  67248. this._textures.dispose();
  67249. };
  67250. /**
  67251. * Disposes the post process.
  67252. * @param camera The camera to dispose the post process on.
  67253. */
  67254. PostProcess.prototype.dispose = function (camera) {
  67255. camera = camera || this._camera;
  67256. this._disposeTextures();
  67257. if (this._scene) {
  67258. var index_1 = this._scene.postProcesses.indexOf(this);
  67259. if (index_1 !== -1) {
  67260. this._scene.postProcesses.splice(index_1, 1);
  67261. }
  67262. }
  67263. else {
  67264. var index_2 = this._engine.postProcesses.indexOf(this);
  67265. if (index_2 !== -1) {
  67266. this._engine.postProcesses.splice(index_2, 1);
  67267. }
  67268. }
  67269. if (!camera) {
  67270. return;
  67271. }
  67272. camera.detachPostProcess(this);
  67273. var index = camera._postProcesses.indexOf(this);
  67274. if (index === 0 && camera._postProcesses.length > 0) {
  67275. var firstPostProcess = this._camera._getFirstPostProcess();
  67276. if (firstPostProcess) {
  67277. firstPostProcess.markTextureDirty();
  67278. }
  67279. }
  67280. this.onActivateObservable.clear();
  67281. this.onAfterRenderObservable.clear();
  67282. this.onApplyObservable.clear();
  67283. this.onBeforeRenderObservable.clear();
  67284. this.onSizeChangedObservable.clear();
  67285. };
  67286. return PostProcess;
  67287. }());
  67288. BABYLON.PostProcess = PostProcess;
  67289. })(BABYLON || (BABYLON = {}));
  67290. //# sourceMappingURL=babylon.postProcess.js.map
  67291. var BABYLON;
  67292. (function (BABYLON) {
  67293. var PassPostProcess = /** @class */ (function (_super) {
  67294. __extends(PassPostProcess, _super);
  67295. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67296. if (camera === void 0) { camera = null; }
  67297. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67298. if (blockCompilation === void 0) { blockCompilation = false; }
  67299. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  67300. }
  67301. return PassPostProcess;
  67302. }(BABYLON.PostProcess));
  67303. BABYLON.PassPostProcess = PassPostProcess;
  67304. })(BABYLON || (BABYLON = {}));
  67305. //# sourceMappingURL=babylon.passPostProcess.js.map
  67306. var __assign = (this && this.__assign) || Object.assign || function(t) {
  67307. for (var s, i = 1, n = arguments.length; i < n; i++) {
  67308. s = arguments[i];
  67309. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  67310. t[p] = s[p];
  67311. }
  67312. return t;
  67313. };
  67314. var BABYLON;
  67315. (function (BABYLON) {
  67316. /**
  67317. * Default implementation IShadowGenerator.
  67318. * This is the main object responsible of generating shadows in the framework.
  67319. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  67320. */
  67321. var ShadowGenerator = /** @class */ (function () {
  67322. /**
  67323. * Creates a ShadowGenerator object.
  67324. * A ShadowGenerator is the required tool to use the shadows.
  67325. * Each light casting shadows needs to use its own ShadowGenerator.
  67326. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  67327. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  67328. * @param light The light object generating the shadows.
  67329. * @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.
  67330. */
  67331. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  67332. this._bias = 0.00005;
  67333. this._normalBias = 0;
  67334. this._blurBoxOffset = 1;
  67335. this._blurScale = 2;
  67336. this._blurKernel = 1;
  67337. this._useKernelBlur = false;
  67338. this._filter = ShadowGenerator.FILTER_NONE;
  67339. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  67340. this._contactHardeningLightSizeUVRatio = 0.1;
  67341. this._darkness = 0;
  67342. this._transparencyShadow = false;
  67343. /**
  67344. * Controls the extent to which the shadows fade out at the edge of the frustum
  67345. * Used only by directionals and spots
  67346. */
  67347. this.frustumEdgeFalloff = 0;
  67348. /**
  67349. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  67350. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  67351. * It might on the other hand introduce peter panning.
  67352. */
  67353. this.forceBackFacesOnly = false;
  67354. this._lightDirection = BABYLON.Vector3.Zero();
  67355. this._viewMatrix = BABYLON.Matrix.Zero();
  67356. this._projectionMatrix = BABYLON.Matrix.Zero();
  67357. this._transformMatrix = BABYLON.Matrix.Zero();
  67358. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67359. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67360. this._currentFaceIndex = 0;
  67361. this._currentFaceIndexCache = 0;
  67362. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  67363. this._mapSize = mapSize;
  67364. this._light = light;
  67365. this._scene = light.getScene();
  67366. light._shadowGenerator = this;
  67367. // Texture type fallback from float to int if not supported.
  67368. var caps = this._scene.getEngine().getCaps();
  67369. if (!useFullFloatFirst) {
  67370. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67371. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67372. }
  67373. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67374. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67375. }
  67376. else {
  67377. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67378. }
  67379. }
  67380. else {
  67381. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67382. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67383. }
  67384. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67385. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67386. }
  67387. else {
  67388. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67389. }
  67390. }
  67391. this._initializeGenerator();
  67392. this._applyFilterValues();
  67393. }
  67394. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  67395. /**
  67396. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  67397. */
  67398. get: function () {
  67399. return this._bias;
  67400. },
  67401. /**
  67402. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  67403. */
  67404. set: function (bias) {
  67405. this._bias = bias;
  67406. },
  67407. enumerable: true,
  67408. configurable: true
  67409. });
  67410. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  67411. /**
  67412. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67413. */
  67414. get: function () {
  67415. return this._normalBias;
  67416. },
  67417. /**
  67418. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67419. */
  67420. set: function (normalBias) {
  67421. this._normalBias = normalBias;
  67422. },
  67423. enumerable: true,
  67424. configurable: true
  67425. });
  67426. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  67427. /**
  67428. * Gets the blur box offset: offset applied during the blur pass.
  67429. * Only usefull if useKernelBlur = false
  67430. */
  67431. get: function () {
  67432. return this._blurBoxOffset;
  67433. },
  67434. /**
  67435. * Sets the blur box offset: offset applied during the blur pass.
  67436. * Only usefull if useKernelBlur = false
  67437. */
  67438. set: function (value) {
  67439. if (this._blurBoxOffset === value) {
  67440. return;
  67441. }
  67442. this._blurBoxOffset = value;
  67443. this._disposeBlurPostProcesses();
  67444. },
  67445. enumerable: true,
  67446. configurable: true
  67447. });
  67448. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  67449. /**
  67450. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  67451. * 2 means half of the size.
  67452. */
  67453. get: function () {
  67454. return this._blurScale;
  67455. },
  67456. /**
  67457. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  67458. * 2 means half of the size.
  67459. */
  67460. set: function (value) {
  67461. if (this._blurScale === value) {
  67462. return;
  67463. }
  67464. this._blurScale = value;
  67465. this._disposeBlurPostProcesses();
  67466. },
  67467. enumerable: true,
  67468. configurable: true
  67469. });
  67470. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  67471. /**
  67472. * Gets the blur kernel: kernel size of the blur pass.
  67473. * Only usefull if useKernelBlur = true
  67474. */
  67475. get: function () {
  67476. return this._blurKernel;
  67477. },
  67478. /**
  67479. * Sets the blur kernel: kernel size of the blur pass.
  67480. * Only usefull if useKernelBlur = true
  67481. */
  67482. set: function (value) {
  67483. if (this._blurKernel === value) {
  67484. return;
  67485. }
  67486. this._blurKernel = value;
  67487. this._disposeBlurPostProcesses();
  67488. },
  67489. enumerable: true,
  67490. configurable: true
  67491. });
  67492. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  67493. /**
  67494. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  67495. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67496. */
  67497. get: function () {
  67498. return this._useKernelBlur;
  67499. },
  67500. /**
  67501. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  67502. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67503. */
  67504. set: function (value) {
  67505. if (this._useKernelBlur === value) {
  67506. return;
  67507. }
  67508. this._useKernelBlur = value;
  67509. this._disposeBlurPostProcesses();
  67510. },
  67511. enumerable: true,
  67512. configurable: true
  67513. });
  67514. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  67515. /**
  67516. * Gets the depth scale used in ESM mode.
  67517. */
  67518. get: function () {
  67519. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  67520. },
  67521. /**
  67522. * Sets the depth scale used in ESM mode.
  67523. * This can override the scale stored on the light.
  67524. */
  67525. set: function (value) {
  67526. this._depthScale = value;
  67527. },
  67528. enumerable: true,
  67529. configurable: true
  67530. });
  67531. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  67532. /**
  67533. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  67534. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67535. */
  67536. get: function () {
  67537. return this._filter;
  67538. },
  67539. /**
  67540. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  67541. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67542. */
  67543. set: function (value) {
  67544. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  67545. if (this._light.needCube()) {
  67546. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67547. this.useExponentialShadowMap = true;
  67548. return;
  67549. }
  67550. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67551. this.useCloseExponentialShadowMap = true;
  67552. return;
  67553. }
  67554. // PCF on cubemap would also be expensive
  67555. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67556. this.usePoissonSampling = true;
  67557. return;
  67558. }
  67559. }
  67560. // Weblg1 fallback for PCF.
  67561. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67562. if (this._scene.getEngine().webGLVersion === 1) {
  67563. this.usePoissonSampling = true;
  67564. return;
  67565. }
  67566. }
  67567. if (this._filter === value) {
  67568. return;
  67569. }
  67570. this._filter = value;
  67571. this._disposeBlurPostProcesses();
  67572. this._applyFilterValues();
  67573. this._light._markMeshesAsLightDirty();
  67574. },
  67575. enumerable: true,
  67576. configurable: true
  67577. });
  67578. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  67579. /**
  67580. * Gets if the current filter is set to Poisson Sampling.
  67581. */
  67582. get: function () {
  67583. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  67584. },
  67585. /**
  67586. * Sets the current filter to Poisson Sampling.
  67587. */
  67588. set: function (value) {
  67589. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  67590. return;
  67591. }
  67592. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  67593. },
  67594. enumerable: true,
  67595. configurable: true
  67596. });
  67597. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  67598. /**
  67599. * Gets if the current filter is set to VSM.
  67600. * DEPRECATED. Should use useExponentialShadowMap instead.
  67601. */
  67602. get: function () {
  67603. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67604. return this.useExponentialShadowMap;
  67605. },
  67606. /**
  67607. * Sets the current filter is to VSM.
  67608. * DEPRECATED. Should use useExponentialShadowMap instead.
  67609. */
  67610. set: function (value) {
  67611. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67612. this.useExponentialShadowMap = value;
  67613. },
  67614. enumerable: true,
  67615. configurable: true
  67616. });
  67617. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  67618. /**
  67619. * Gets if the current filter is set to blurred VSM.
  67620. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67621. */
  67622. get: function () {
  67623. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67624. return this.useBlurExponentialShadowMap;
  67625. },
  67626. /**
  67627. * Sets the current filter is to blurred VSM.
  67628. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67629. */
  67630. set: function (value) {
  67631. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67632. this.useBlurExponentialShadowMap = value;
  67633. },
  67634. enumerable: true,
  67635. configurable: true
  67636. });
  67637. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  67638. /**
  67639. * Gets if the current filter is set to ESM.
  67640. */
  67641. get: function () {
  67642. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  67643. },
  67644. /**
  67645. * Sets the current filter is to ESM.
  67646. */
  67647. set: function (value) {
  67648. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  67649. return;
  67650. }
  67651. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67652. },
  67653. enumerable: true,
  67654. configurable: true
  67655. });
  67656. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  67657. /**
  67658. * Gets if the current filter is set to filtered ESM.
  67659. */
  67660. get: function () {
  67661. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  67662. },
  67663. /**
  67664. * Gets if the current filter is set to filtered ESM.
  67665. */
  67666. set: function (value) {
  67667. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67668. return;
  67669. }
  67670. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67671. },
  67672. enumerable: true,
  67673. configurable: true
  67674. });
  67675. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  67676. /**
  67677. * Gets if the current filter is set to "close ESM" (using the inverse of the
  67678. * exponential to prevent steep falloff artifacts).
  67679. */
  67680. get: function () {
  67681. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  67682. },
  67683. /**
  67684. * Sets the current filter to "close ESM" (using the inverse of the
  67685. * exponential to prevent steep falloff artifacts).
  67686. */
  67687. set: function (value) {
  67688. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  67689. return;
  67690. }
  67691. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67692. },
  67693. enumerable: true,
  67694. configurable: true
  67695. });
  67696. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  67697. /**
  67698. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  67699. * exponential to prevent steep falloff artifacts).
  67700. */
  67701. get: function () {
  67702. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  67703. },
  67704. /**
  67705. * Sets the current filter to filtered "close ESM" (using the inverse of the
  67706. * exponential to prevent steep falloff artifacts).
  67707. */
  67708. set: function (value) {
  67709. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67710. return;
  67711. }
  67712. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67713. },
  67714. enumerable: true,
  67715. configurable: true
  67716. });
  67717. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  67718. /**
  67719. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  67720. */
  67721. get: function () {
  67722. return this.filter === ShadowGenerator.FILTER_PCF;
  67723. },
  67724. /**
  67725. * Sets the current filter to "PCF" (percentage closer filtering).
  67726. */
  67727. set: function (value) {
  67728. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  67729. return;
  67730. }
  67731. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  67732. },
  67733. enumerable: true,
  67734. configurable: true
  67735. });
  67736. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  67737. /**
  67738. * Gets the PCF or PCSS Quality.
  67739. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67740. */
  67741. get: function () {
  67742. return this._filteringQuality;
  67743. },
  67744. /**
  67745. * Sets the PCF or PCSS Quality.
  67746. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67747. */
  67748. set: function (filteringQuality) {
  67749. this._filteringQuality = filteringQuality;
  67750. },
  67751. enumerable: true,
  67752. configurable: true
  67753. });
  67754. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  67755. /**
  67756. * Gets if the current filter is set to "PCSS" (contact hardening).
  67757. */
  67758. get: function () {
  67759. return this.filter === ShadowGenerator.FILTER_PCSS;
  67760. },
  67761. /**
  67762. * Sets the current filter to "PCSS" (contact hardening).
  67763. */
  67764. set: function (value) {
  67765. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  67766. return;
  67767. }
  67768. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  67769. },
  67770. enumerable: true,
  67771. configurable: true
  67772. });
  67773. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  67774. /**
  67775. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67776. * Using a ratio helps keeping shape stability independently of the map size.
  67777. *
  67778. * It does not account for the light projection as it was having too much
  67779. * instability during the light setup or during light position changes.
  67780. *
  67781. * Only valid if useContactHardeningShadow is true.
  67782. */
  67783. get: function () {
  67784. return this._contactHardeningLightSizeUVRatio;
  67785. },
  67786. /**
  67787. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67788. * Using a ratio helps keeping shape stability independently of the map size.
  67789. *
  67790. * It does not account for the light projection as it was having too much
  67791. * instability during the light setup or during light position changes.
  67792. *
  67793. * Only valid if useContactHardeningShadow is true.
  67794. */
  67795. set: function (contactHardeningLightSizeUVRatio) {
  67796. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  67797. },
  67798. enumerable: true,
  67799. configurable: true
  67800. });
  67801. /**
  67802. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  67803. * 0 means strongest and 1 would means no shadow.
  67804. * @returns the darkness.
  67805. */
  67806. ShadowGenerator.prototype.getDarkness = function () {
  67807. return this._darkness;
  67808. };
  67809. /**
  67810. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  67811. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  67812. * @returns the shadow generator allowing fluent coding.
  67813. */
  67814. ShadowGenerator.prototype.setDarkness = function (darkness) {
  67815. if (darkness >= 1.0)
  67816. this._darkness = 1.0;
  67817. else if (darkness <= 0.0)
  67818. this._darkness = 0.0;
  67819. else
  67820. this._darkness = darkness;
  67821. return this;
  67822. };
  67823. /**
  67824. * Sets the ability to have transparent shadow (boolean).
  67825. * @param transparent True if transparent else False
  67826. * @returns the shadow generator allowing fluent coding
  67827. */
  67828. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  67829. this._transparencyShadow = transparent;
  67830. return this;
  67831. };
  67832. /**
  67833. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  67834. * @returns The render target texture if present otherwise, null
  67835. */
  67836. ShadowGenerator.prototype.getShadowMap = function () {
  67837. return this._shadowMap;
  67838. };
  67839. /**
  67840. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  67841. * @returns The render target texture if the shadow map is present otherwise, null
  67842. */
  67843. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  67844. if (this._shadowMap2) {
  67845. return this._shadowMap2;
  67846. }
  67847. return this._shadowMap;
  67848. };
  67849. /**
  67850. * Helper function to add a mesh and its descendants to the list of shadow casters.
  67851. * @param mesh Mesh to add
  67852. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  67853. * @returns the Shadow Generator itself
  67854. */
  67855. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  67856. if (includeDescendants === void 0) { includeDescendants = true; }
  67857. if (!this._shadowMap) {
  67858. return this;
  67859. }
  67860. if (!this._shadowMap.renderList) {
  67861. this._shadowMap.renderList = [];
  67862. }
  67863. this._shadowMap.renderList.push(mesh);
  67864. if (includeDescendants) {
  67865. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  67866. }
  67867. return this;
  67868. var _a;
  67869. };
  67870. /**
  67871. * Helper function to remove a mesh and its descendants from the list of shadow casters
  67872. * @param mesh Mesh to remove
  67873. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  67874. * @returns the Shadow Generator itself
  67875. */
  67876. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  67877. if (includeDescendants === void 0) { includeDescendants = true; }
  67878. if (!this._shadowMap || !this._shadowMap.renderList) {
  67879. return this;
  67880. }
  67881. var index = this._shadowMap.renderList.indexOf(mesh);
  67882. if (index !== -1) {
  67883. this._shadowMap.renderList.splice(index, 1);
  67884. }
  67885. if (includeDescendants) {
  67886. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  67887. var child = _a[_i];
  67888. this.removeShadowCaster(child);
  67889. }
  67890. }
  67891. return this;
  67892. };
  67893. /**
  67894. * Returns the associated light object.
  67895. * @returns the light generating the shadow
  67896. */
  67897. ShadowGenerator.prototype.getLight = function () {
  67898. return this._light;
  67899. };
  67900. ShadowGenerator.prototype._initializeGenerator = function () {
  67901. this._light._markMeshesAsLightDirty();
  67902. this._initializeShadowMap();
  67903. };
  67904. ShadowGenerator.prototype._initializeShadowMap = function () {
  67905. var _this = this;
  67906. // Render target
  67907. var engine = this._scene.getEngine();
  67908. if (engine.webGLVersion > 1) {
  67909. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  67910. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  67911. }
  67912. else {
  67913. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  67914. }
  67915. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67916. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67917. this._shadowMap.anisotropicFilteringLevel = 1;
  67918. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67919. this._shadowMap.renderParticles = false;
  67920. this._shadowMap.ignoreCameraViewport = true;
  67921. // Record Face Index before render.
  67922. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  67923. _this._currentFaceIndex = faceIndex;
  67924. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67925. engine.setColorWrite(false);
  67926. }
  67927. });
  67928. // Custom render function.
  67929. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  67930. // Blur if required afer render.
  67931. this._shadowMap.onAfterUnbindObservable.add(function () {
  67932. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67933. engine.setColorWrite(true);
  67934. }
  67935. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  67936. return;
  67937. }
  67938. var shadowMap = _this.getShadowMapForRendering();
  67939. if (shadowMap) {
  67940. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  67941. }
  67942. });
  67943. // Clear according to the chosen filter.
  67944. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  67945. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  67946. this._shadowMap.onClearObservable.add(function (engine) {
  67947. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67948. engine.clear(clearOne, false, true, false);
  67949. }
  67950. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  67951. engine.clear(clearZero, true, true, false);
  67952. }
  67953. else {
  67954. engine.clear(clearOne, true, true, false);
  67955. }
  67956. });
  67957. };
  67958. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  67959. var _this = this;
  67960. var engine = this._scene.getEngine();
  67961. var targetSize = this._mapSize / this.blurScale;
  67962. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  67963. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  67964. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67965. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67966. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67967. }
  67968. if (this.useKernelBlur) {
  67969. 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);
  67970. this._kernelBlurXPostprocess.width = targetSize;
  67971. this._kernelBlurXPostprocess.height = targetSize;
  67972. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  67973. effect.setTexture("textureSampler", _this._shadowMap);
  67974. });
  67975. 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);
  67976. this._kernelBlurXPostprocess.autoClear = false;
  67977. this._kernelBlurYPostprocess.autoClear = false;
  67978. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67979. this._kernelBlurXPostprocess.packedFloat = true;
  67980. this._kernelBlurYPostprocess.packedFloat = true;
  67981. }
  67982. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  67983. }
  67984. else {
  67985. 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);
  67986. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  67987. effect.setFloat2("screenSize", targetSize, targetSize);
  67988. effect.setTexture("textureSampler", _this._shadowMap);
  67989. });
  67990. this._boxBlurPostprocess.autoClear = false;
  67991. this._blurPostProcesses = [this._boxBlurPostprocess];
  67992. }
  67993. };
  67994. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67995. var index;
  67996. var engine = this._scene.getEngine();
  67997. if (depthOnlySubMeshes.length) {
  67998. engine.setColorWrite(false);
  67999. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68000. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  68001. }
  68002. engine.setColorWrite(true);
  68003. }
  68004. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68005. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  68006. }
  68007. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68008. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  68009. }
  68010. if (this._transparencyShadow) {
  68011. for (index = 0; index < transparentSubMeshes.length; index++) {
  68012. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  68013. }
  68014. }
  68015. };
  68016. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  68017. var _this = this;
  68018. var mesh = subMesh.getRenderingMesh();
  68019. var scene = this._scene;
  68020. var engine = scene.getEngine();
  68021. var material = subMesh.getMaterial();
  68022. if (!material) {
  68023. return;
  68024. }
  68025. // Culling
  68026. engine.setState(material.backFaceCulling);
  68027. // Managing instances
  68028. var batch = mesh._getInstancesRenderList(subMesh._id);
  68029. if (batch.mustReturn) {
  68030. return;
  68031. }
  68032. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68033. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  68034. engine.enableEffect(this._effect);
  68035. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  68036. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  68037. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  68038. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68039. this._effect.setVector3("lightData", this._cachedDirection);
  68040. }
  68041. else {
  68042. this._effect.setVector3("lightData", this._cachedPosition);
  68043. }
  68044. if (scene.activeCamera) {
  68045. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  68046. }
  68047. // Alpha test
  68048. if (material && material.needAlphaTesting()) {
  68049. var alphaTexture = material.getAlphaTestTexture();
  68050. if (alphaTexture) {
  68051. this._effect.setTexture("diffuseSampler", alphaTexture);
  68052. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  68053. }
  68054. }
  68055. // Bones
  68056. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68057. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  68058. }
  68059. // Morph targets
  68060. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  68061. if (this.forceBackFacesOnly) {
  68062. engine.setState(true, 0, false, true);
  68063. }
  68064. // Draw
  68065. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68066. if (this.forceBackFacesOnly) {
  68067. engine.setState(true, 0, false, false);
  68068. }
  68069. }
  68070. else {
  68071. // Need to reset refresh rate of the shadowMap
  68072. if (this._shadowMap) {
  68073. this._shadowMap.resetRefreshCounter();
  68074. }
  68075. }
  68076. };
  68077. ShadowGenerator.prototype._applyFilterValues = function () {
  68078. if (!this._shadowMap) {
  68079. return;
  68080. }
  68081. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  68082. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  68083. }
  68084. else {
  68085. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68086. }
  68087. };
  68088. /**
  68089. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68090. * @param onCompiled Callback triggered at the and of the effects compilation
  68091. * @param options Sets of optional options forcing the compilation with different modes
  68092. */
  68093. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  68094. var _this = this;
  68095. var localOptions = __assign({ useInstances: false }, options);
  68096. var shadowMap = this.getShadowMap();
  68097. if (!shadowMap) {
  68098. if (onCompiled) {
  68099. onCompiled(this);
  68100. }
  68101. return;
  68102. }
  68103. var renderList = shadowMap.renderList;
  68104. if (!renderList) {
  68105. if (onCompiled) {
  68106. onCompiled(this);
  68107. }
  68108. return;
  68109. }
  68110. var subMeshes = new Array();
  68111. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  68112. var mesh = renderList_1[_i];
  68113. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  68114. }
  68115. if (subMeshes.length === 0) {
  68116. if (onCompiled) {
  68117. onCompiled(this);
  68118. }
  68119. return;
  68120. }
  68121. var currentIndex = 0;
  68122. var checkReady = function () {
  68123. if (!_this._scene || !_this._scene.getEngine()) {
  68124. return;
  68125. }
  68126. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  68127. currentIndex++;
  68128. if (currentIndex >= subMeshes.length) {
  68129. if (onCompiled) {
  68130. onCompiled(_this);
  68131. }
  68132. return;
  68133. }
  68134. }
  68135. setTimeout(checkReady, 16);
  68136. };
  68137. checkReady();
  68138. };
  68139. /**
  68140. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68141. * @param options Sets of optional options forcing the compilation with different modes
  68142. * @returns A promise that resolves when the compilation completes
  68143. */
  68144. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  68145. var _this = this;
  68146. return new Promise(function (resolve) {
  68147. _this.forceCompilation(function () {
  68148. resolve();
  68149. }, options);
  68150. });
  68151. };
  68152. /**
  68153. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  68154. * @param subMesh The submesh we want to render in the shadow map
  68155. * @param useInstances Defines wether will draw in the map using instances
  68156. * @returns true if ready otherwise, false
  68157. */
  68158. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  68159. var defines = [];
  68160. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68161. defines.push("#define FLOAT");
  68162. }
  68163. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68164. defines.push("#define ESM");
  68165. }
  68166. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  68167. defines.push("#define DEPTHTEXTURE");
  68168. }
  68169. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68170. var mesh = subMesh.getMesh();
  68171. var material = subMesh.getMaterial();
  68172. // Normal bias.
  68173. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68174. attribs.push(BABYLON.VertexBuffer.NormalKind);
  68175. defines.push("#define NORMAL");
  68176. if (mesh.nonUniformScaling) {
  68177. defines.push("#define NONUNIFORMSCALING");
  68178. }
  68179. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68180. defines.push("#define DIRECTIONINLIGHTDATA");
  68181. }
  68182. }
  68183. // Alpha test
  68184. if (material && material.needAlphaTesting()) {
  68185. var alphaTexture = material.getAlphaTestTexture();
  68186. if (alphaTexture) {
  68187. defines.push("#define ALPHATEST");
  68188. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68189. attribs.push(BABYLON.VertexBuffer.UVKind);
  68190. defines.push("#define UV1");
  68191. }
  68192. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68193. if (alphaTexture.coordinatesIndex === 1) {
  68194. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68195. defines.push("#define UV2");
  68196. }
  68197. }
  68198. }
  68199. }
  68200. // Bones
  68201. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68202. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68203. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68204. if (mesh.numBoneInfluencers > 4) {
  68205. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68206. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68207. }
  68208. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68209. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68210. }
  68211. else {
  68212. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68213. }
  68214. // Morph targets
  68215. var manager = mesh.morphTargetManager;
  68216. var morphInfluencers = 0;
  68217. if (manager) {
  68218. if (manager.numInfluencers > 0) {
  68219. defines.push("#define MORPHTARGETS");
  68220. morphInfluencers = manager.numInfluencers;
  68221. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  68222. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  68223. }
  68224. }
  68225. // Instances
  68226. if (useInstances) {
  68227. defines.push("#define INSTANCES");
  68228. attribs.push("world0");
  68229. attribs.push("world1");
  68230. attribs.push("world2");
  68231. attribs.push("world3");
  68232. }
  68233. // Get correct effect
  68234. var join = defines.join("\n");
  68235. if (this._cachedDefines !== join) {
  68236. this._cachedDefines = join;
  68237. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  68238. }
  68239. if (!this._effect.isReady()) {
  68240. return false;
  68241. }
  68242. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68243. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  68244. this._initializeBlurRTTAndPostProcesses();
  68245. }
  68246. }
  68247. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  68248. return false;
  68249. }
  68250. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  68251. return false;
  68252. }
  68253. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  68254. return false;
  68255. }
  68256. return true;
  68257. };
  68258. /**
  68259. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  68260. * @param defines Defines of the material we want to update
  68261. * @param lightIndex Index of the light in the enabled light list of the material
  68262. */
  68263. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  68264. var scene = this._scene;
  68265. var light = this._light;
  68266. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68267. return;
  68268. }
  68269. defines["SHADOW" + lightIndex] = true;
  68270. if (this.useContactHardeningShadow) {
  68271. defines["SHADOWPCSS" + lightIndex] = true;
  68272. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68273. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68274. }
  68275. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68276. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68277. }
  68278. // else default to high.
  68279. }
  68280. if (this.usePercentageCloserFiltering) {
  68281. defines["SHADOWPCF" + lightIndex] = true;
  68282. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68283. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68284. }
  68285. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68286. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68287. }
  68288. // else default to high.
  68289. }
  68290. else if (this.usePoissonSampling) {
  68291. defines["SHADOWPOISSON" + lightIndex] = true;
  68292. }
  68293. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68294. defines["SHADOWESM" + lightIndex] = true;
  68295. }
  68296. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68297. defines["SHADOWCLOSEESM" + lightIndex] = true;
  68298. }
  68299. if (light.needCube()) {
  68300. defines["SHADOWCUBE" + lightIndex] = true;
  68301. }
  68302. };
  68303. /**
  68304. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  68305. * defined in the generator but impacting the effect).
  68306. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  68307. * @param effect The effect we are binfing the information for
  68308. */
  68309. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  68310. var light = this._light;
  68311. var scene = this._scene;
  68312. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68313. return;
  68314. }
  68315. var camera = scene.activeCamera;
  68316. if (!camera) {
  68317. return;
  68318. }
  68319. var shadowMap = this.getShadowMap();
  68320. if (!shadowMap) {
  68321. return;
  68322. }
  68323. if (!light.needCube()) {
  68324. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  68325. }
  68326. // Only PCF uses depth stencil texture.
  68327. if (this._filter === ShadowGenerator.FILTER_PCF) {
  68328. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68329. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68330. }
  68331. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  68332. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68333. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  68334. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68335. }
  68336. else {
  68337. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68338. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  68339. }
  68340. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  68341. };
  68342. /**
  68343. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  68344. * (eq to shadow prjection matrix * light transform matrix)
  68345. * @returns The transform matrix used to create the shadow map
  68346. */
  68347. ShadowGenerator.prototype.getTransformMatrix = function () {
  68348. var scene = this._scene;
  68349. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  68350. return this._transformMatrix;
  68351. }
  68352. this._currentRenderID = scene.getRenderId();
  68353. this._currentFaceIndexCache = this._currentFaceIndex;
  68354. var lightPosition = this._light.position;
  68355. if (this._light.computeTransformedInformation()) {
  68356. lightPosition = this._light.transformedPosition;
  68357. }
  68358. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  68359. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  68360. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  68361. }
  68362. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  68363. this._cachedPosition.copyFrom(lightPosition);
  68364. this._cachedDirection.copyFrom(this._lightDirection);
  68365. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  68366. var shadowMap = this.getShadowMap();
  68367. if (shadowMap) {
  68368. var renderList = shadowMap.renderList;
  68369. if (renderList) {
  68370. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  68371. }
  68372. }
  68373. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  68374. }
  68375. return this._transformMatrix;
  68376. };
  68377. /**
  68378. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  68379. * Cube and 2D textures for instance.
  68380. */
  68381. ShadowGenerator.prototype.recreateShadowMap = function () {
  68382. var shadowMap = this._shadowMap;
  68383. if (!shadowMap) {
  68384. return;
  68385. }
  68386. // Track render list.
  68387. var renderList = shadowMap.renderList;
  68388. // Clean up existing data.
  68389. this._disposeRTTandPostProcesses();
  68390. // Reinitializes.
  68391. this._initializeGenerator();
  68392. // Reaffect the filter to ensure a correct fallback if necessary.
  68393. this.filter = this.filter;
  68394. // Reaffect the filter.
  68395. this._applyFilterValues();
  68396. // Reaffect Render List.
  68397. this._shadowMap.renderList = renderList;
  68398. };
  68399. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  68400. if (this._shadowMap2) {
  68401. this._shadowMap2.dispose();
  68402. this._shadowMap2 = null;
  68403. }
  68404. if (this._boxBlurPostprocess) {
  68405. this._boxBlurPostprocess.dispose();
  68406. this._boxBlurPostprocess = null;
  68407. }
  68408. if (this._kernelBlurXPostprocess) {
  68409. this._kernelBlurXPostprocess.dispose();
  68410. this._kernelBlurXPostprocess = null;
  68411. }
  68412. if (this._kernelBlurYPostprocess) {
  68413. this._kernelBlurYPostprocess.dispose();
  68414. this._kernelBlurYPostprocess = null;
  68415. }
  68416. this._blurPostProcesses = [];
  68417. };
  68418. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  68419. if (this._shadowMap) {
  68420. this._shadowMap.dispose();
  68421. this._shadowMap = null;
  68422. }
  68423. this._disposeBlurPostProcesses();
  68424. };
  68425. /**
  68426. * Disposes the ShadowGenerator.
  68427. * Returns nothing.
  68428. */
  68429. ShadowGenerator.prototype.dispose = function () {
  68430. this._disposeRTTandPostProcesses();
  68431. if (this._light) {
  68432. this._light._shadowGenerator = null;
  68433. this._light._markMeshesAsLightDirty();
  68434. }
  68435. };
  68436. /**
  68437. * Serializes the shadow generator setup to a json object.
  68438. * @returns The serialized JSON object
  68439. */
  68440. ShadowGenerator.prototype.serialize = function () {
  68441. var serializationObject = {};
  68442. var shadowMap = this.getShadowMap();
  68443. if (!shadowMap) {
  68444. return serializationObject;
  68445. }
  68446. serializationObject.lightId = this._light.id;
  68447. serializationObject.mapSize = shadowMap.getRenderSize();
  68448. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  68449. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  68450. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68451. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68452. serializationObject.usePoissonSampling = this.usePoissonSampling;
  68453. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  68454. serializationObject.depthScale = this.depthScale;
  68455. serializationObject.darkness = this.getDarkness();
  68456. serializationObject.blurBoxOffset = this.blurBoxOffset;
  68457. serializationObject.blurKernel = this.blurKernel;
  68458. serializationObject.blurScale = this.blurScale;
  68459. serializationObject.useKernelBlur = this.useKernelBlur;
  68460. serializationObject.transparencyShadow = this._transparencyShadow;
  68461. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  68462. serializationObject.bias = this.bias;
  68463. serializationObject.normalBias = this.normalBias;
  68464. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  68465. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  68466. serializationObject.filteringQuality = this.filteringQuality;
  68467. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  68468. serializationObject.renderList = [];
  68469. if (shadowMap.renderList) {
  68470. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  68471. var mesh = shadowMap.renderList[meshIndex];
  68472. serializationObject.renderList.push(mesh.id);
  68473. }
  68474. }
  68475. return serializationObject;
  68476. };
  68477. /**
  68478. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  68479. * @param parsedShadowGenerator The JSON object to parse
  68480. * @param scene The scene to create the shadow map for
  68481. * @returns The parsed shadow generator
  68482. */
  68483. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  68484. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  68485. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  68486. var shadowMap = shadowGenerator.getShadowMap();
  68487. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  68488. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  68489. meshes.forEach(function (mesh) {
  68490. if (!shadowMap) {
  68491. return;
  68492. }
  68493. if (!shadowMap.renderList) {
  68494. shadowMap.renderList = [];
  68495. }
  68496. shadowMap.renderList.push(mesh);
  68497. });
  68498. }
  68499. if (parsedShadowGenerator.usePoissonSampling) {
  68500. shadowGenerator.usePoissonSampling = true;
  68501. }
  68502. else if (parsedShadowGenerator.useExponentialShadowMap) {
  68503. shadowGenerator.useExponentialShadowMap = true;
  68504. }
  68505. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  68506. shadowGenerator.useBlurExponentialShadowMap = true;
  68507. }
  68508. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  68509. shadowGenerator.useCloseExponentialShadowMap = true;
  68510. }
  68511. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  68512. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  68513. }
  68514. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  68515. shadowGenerator.usePercentageCloserFiltering = true;
  68516. }
  68517. else if (parsedShadowGenerator.useContactHardeningShadow) {
  68518. shadowGenerator.useContactHardeningShadow = true;
  68519. }
  68520. if (parsedShadowGenerator.filteringQuality) {
  68521. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  68522. }
  68523. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  68524. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  68525. }
  68526. // Backward compat
  68527. else if (parsedShadowGenerator.useVarianceShadowMap) {
  68528. shadowGenerator.useExponentialShadowMap = true;
  68529. }
  68530. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  68531. shadowGenerator.useBlurExponentialShadowMap = true;
  68532. }
  68533. if (parsedShadowGenerator.depthScale) {
  68534. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  68535. }
  68536. if (parsedShadowGenerator.blurScale) {
  68537. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  68538. }
  68539. if (parsedShadowGenerator.blurBoxOffset) {
  68540. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  68541. }
  68542. if (parsedShadowGenerator.useKernelBlur) {
  68543. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  68544. }
  68545. if (parsedShadowGenerator.blurKernel) {
  68546. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  68547. }
  68548. if (parsedShadowGenerator.bias !== undefined) {
  68549. shadowGenerator.bias = parsedShadowGenerator.bias;
  68550. }
  68551. if (parsedShadowGenerator.normalBias !== undefined) {
  68552. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  68553. }
  68554. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  68555. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  68556. }
  68557. if (parsedShadowGenerator.darkness) {
  68558. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  68559. }
  68560. if (parsedShadowGenerator.transparencyShadow) {
  68561. shadowGenerator.setTransparencyShadow(true);
  68562. }
  68563. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  68564. return shadowGenerator;
  68565. };
  68566. /**
  68567. * Shadow generator mode None: no filtering applied.
  68568. */
  68569. ShadowGenerator.FILTER_NONE = 0;
  68570. /**
  68571. * Shadow generator mode ESM: Exponential Shadow Mapping.
  68572. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68573. */
  68574. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  68575. /**
  68576. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  68577. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  68578. */
  68579. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  68580. /**
  68581. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  68582. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68583. */
  68584. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  68585. /**
  68586. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  68587. * edge artifacts on steep falloff.
  68588. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68589. */
  68590. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  68591. /**
  68592. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  68593. * edge artifacts on steep falloff.
  68594. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68595. */
  68596. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  68597. /**
  68598. * Shadow generator mode PCF: Percentage Closer Filtering
  68599. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68600. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  68601. */
  68602. ShadowGenerator.FILTER_PCF = 6;
  68603. /**
  68604. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  68605. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68606. * Contact Hardening
  68607. */
  68608. ShadowGenerator.FILTER_PCSS = 7;
  68609. /**
  68610. * Reserved for PCF and PCSS
  68611. * Highest Quality.
  68612. *
  68613. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  68614. *
  68615. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  68616. */
  68617. ShadowGenerator.QUALITY_HIGH = 0;
  68618. /**
  68619. * Reserved for PCF and PCSS
  68620. * Good tradeoff for quality/perf cross devices
  68621. *
  68622. * Execute PCF on a 3*3 kernel.
  68623. *
  68624. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  68625. */
  68626. ShadowGenerator.QUALITY_MEDIUM = 1;
  68627. /**
  68628. * Reserved for PCF and PCSS
  68629. * The lowest quality but the fastest.
  68630. *
  68631. * Execute PCF on a 1*1 kernel.
  68632. *
  68633. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  68634. */
  68635. ShadowGenerator.QUALITY_LOW = 2;
  68636. return ShadowGenerator;
  68637. }());
  68638. BABYLON.ShadowGenerator = ShadowGenerator;
  68639. })(BABYLON || (BABYLON = {}));
  68640. //# sourceMappingURL=babylon.shadowGenerator.js.map
  68641. var BABYLON;
  68642. (function (BABYLON) {
  68643. var DefaultLoadingScreen = /** @class */ (function () {
  68644. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  68645. if (_loadingText === void 0) { _loadingText = ""; }
  68646. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  68647. var _this = this;
  68648. this._renderingCanvas = _renderingCanvas;
  68649. this._loadingText = _loadingText;
  68650. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  68651. // Resize
  68652. this._resizeLoadingUI = function () {
  68653. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  68654. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  68655. if (!_this._loadingDiv) {
  68656. return;
  68657. }
  68658. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  68659. _this._loadingDiv.style.left = canvasRect.left + "px";
  68660. _this._loadingDiv.style.top = canvasRect.top + "px";
  68661. _this._loadingDiv.style.width = canvasRect.width + "px";
  68662. _this._loadingDiv.style.height = canvasRect.height + "px";
  68663. };
  68664. }
  68665. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  68666. if (this._loadingDiv) {
  68667. // Do not add a loading screen if there is already one
  68668. return;
  68669. }
  68670. this._loadingDiv = document.createElement("div");
  68671. this._loadingDiv.id = "babylonjsLoadingDiv";
  68672. this._loadingDiv.style.opacity = "0";
  68673. this._loadingDiv.style.transition = "opacity 1.5s ease";
  68674. this._loadingDiv.style.pointerEvents = "none";
  68675. // Loading text
  68676. this._loadingTextDiv = document.createElement("div");
  68677. this._loadingTextDiv.style.position = "absolute";
  68678. this._loadingTextDiv.style.left = "0";
  68679. this._loadingTextDiv.style.top = "50%";
  68680. this._loadingTextDiv.style.marginTop = "80px";
  68681. this._loadingTextDiv.style.width = "100%";
  68682. this._loadingTextDiv.style.height = "20px";
  68683. this._loadingTextDiv.style.fontFamily = "Arial";
  68684. this._loadingTextDiv.style.fontSize = "14px";
  68685. this._loadingTextDiv.style.color = "white";
  68686. this._loadingTextDiv.style.textAlign = "center";
  68687. this._loadingTextDiv.innerHTML = "Loading";
  68688. this._loadingDiv.appendChild(this._loadingTextDiv);
  68689. //set the predefined text
  68690. this._loadingTextDiv.innerHTML = this._loadingText;
  68691. // Generating keyframes
  68692. var style = document.createElement('style');
  68693. style.type = 'text/css';
  68694. 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 }";
  68695. style.innerHTML = keyFrames;
  68696. document.getElementsByTagName('head')[0].appendChild(style);
  68697. // Loading img
  68698. var imgBack = new Image();
  68699. 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";
  68700. imgBack.style.position = "absolute";
  68701. imgBack.style.left = "50%";
  68702. imgBack.style.top = "50%";
  68703. imgBack.style.marginLeft = "-60px";
  68704. imgBack.style.marginTop = "-60px";
  68705. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  68706. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  68707. imgBack.style.transformOrigin = "50% 50%";
  68708. imgBack.style.webkitTransformOrigin = "50% 50%";
  68709. this._loadingDiv.appendChild(imgBack);
  68710. this._resizeLoadingUI();
  68711. window.addEventListener("resize", this._resizeLoadingUI);
  68712. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68713. document.body.appendChild(this._loadingDiv);
  68714. this._loadingDiv.style.opacity = "1";
  68715. };
  68716. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  68717. var _this = this;
  68718. if (!this._loadingDiv) {
  68719. return;
  68720. }
  68721. var onTransitionEnd = function () {
  68722. if (!_this._loadingDiv) {
  68723. return;
  68724. }
  68725. document.body.removeChild(_this._loadingDiv);
  68726. window.removeEventListener("resize", _this._resizeLoadingUI);
  68727. _this._loadingDiv = null;
  68728. };
  68729. this._loadingDiv.style.opacity = "0";
  68730. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  68731. };
  68732. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  68733. set: function (text) {
  68734. this._loadingText = text;
  68735. if (this._loadingTextDiv) {
  68736. this._loadingTextDiv.innerHTML = this._loadingText;
  68737. }
  68738. },
  68739. enumerable: true,
  68740. configurable: true
  68741. });
  68742. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  68743. get: function () {
  68744. return this._loadingDivBackgroundColor;
  68745. },
  68746. set: function (color) {
  68747. this._loadingDivBackgroundColor = color;
  68748. if (!this._loadingDiv) {
  68749. return;
  68750. }
  68751. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68752. },
  68753. enumerable: true,
  68754. configurable: true
  68755. });
  68756. return DefaultLoadingScreen;
  68757. }());
  68758. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  68759. })(BABYLON || (BABYLON = {}));
  68760. //# sourceMappingURL=babylon.loadingScreen.js.map
  68761. var BABYLON;
  68762. (function (BABYLON) {
  68763. var SceneLoaderProgressEvent = /** @class */ (function () {
  68764. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  68765. this.lengthComputable = lengthComputable;
  68766. this.loaded = loaded;
  68767. this.total = total;
  68768. }
  68769. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  68770. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  68771. };
  68772. return SceneLoaderProgressEvent;
  68773. }());
  68774. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  68775. var SceneLoader = /** @class */ (function () {
  68776. function SceneLoader() {
  68777. }
  68778. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  68779. get: function () {
  68780. return 0;
  68781. },
  68782. enumerable: true,
  68783. configurable: true
  68784. });
  68785. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  68786. get: function () {
  68787. return 1;
  68788. },
  68789. enumerable: true,
  68790. configurable: true
  68791. });
  68792. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  68793. get: function () {
  68794. return 2;
  68795. },
  68796. enumerable: true,
  68797. configurable: true
  68798. });
  68799. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  68800. get: function () {
  68801. return 3;
  68802. },
  68803. enumerable: true,
  68804. configurable: true
  68805. });
  68806. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  68807. get: function () {
  68808. return SceneLoader._ForceFullSceneLoadingForIncremental;
  68809. },
  68810. set: function (value) {
  68811. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  68812. },
  68813. enumerable: true,
  68814. configurable: true
  68815. });
  68816. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  68817. get: function () {
  68818. return SceneLoader._ShowLoadingScreen;
  68819. },
  68820. set: function (value) {
  68821. SceneLoader._ShowLoadingScreen = value;
  68822. },
  68823. enumerable: true,
  68824. configurable: true
  68825. });
  68826. Object.defineProperty(SceneLoader, "loggingLevel", {
  68827. get: function () {
  68828. return SceneLoader._loggingLevel;
  68829. },
  68830. set: function (value) {
  68831. SceneLoader._loggingLevel = value;
  68832. },
  68833. enumerable: true,
  68834. configurable: true
  68835. });
  68836. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  68837. get: function () {
  68838. return SceneLoader._CleanBoneMatrixWeights;
  68839. },
  68840. set: function (value) {
  68841. SceneLoader._CleanBoneMatrixWeights = value;
  68842. },
  68843. enumerable: true,
  68844. configurable: true
  68845. });
  68846. SceneLoader._getDefaultPlugin = function () {
  68847. return SceneLoader._registeredPlugins[".babylon"];
  68848. };
  68849. SceneLoader._getPluginForExtension = function (extension) {
  68850. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  68851. if (registeredPlugin) {
  68852. return registeredPlugin;
  68853. }
  68854. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  68855. return SceneLoader._getDefaultPlugin();
  68856. };
  68857. SceneLoader._getPluginForDirectLoad = function (data) {
  68858. for (var extension in SceneLoader._registeredPlugins) {
  68859. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  68860. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  68861. return SceneLoader._registeredPlugins[extension];
  68862. }
  68863. }
  68864. return SceneLoader._getDefaultPlugin();
  68865. };
  68866. SceneLoader._getPluginForFilename = function (sceneFilename) {
  68867. if (sceneFilename.name) {
  68868. sceneFilename = sceneFilename.name;
  68869. }
  68870. var queryStringPosition = sceneFilename.indexOf("?");
  68871. if (queryStringPosition !== -1) {
  68872. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  68873. }
  68874. var dotPosition = sceneFilename.lastIndexOf(".");
  68875. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  68876. return SceneLoader._getPluginForExtension(extension);
  68877. };
  68878. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  68879. SceneLoader._getDirectLoad = function (sceneFilename) {
  68880. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  68881. return sceneFilename.substr(5);
  68882. }
  68883. return null;
  68884. };
  68885. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  68886. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  68887. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  68888. var plugin;
  68889. if (registeredPlugin.plugin.createPlugin) {
  68890. plugin = registeredPlugin.plugin.createPlugin();
  68891. }
  68892. else {
  68893. plugin = registeredPlugin.plugin;
  68894. }
  68895. var useArrayBuffer = registeredPlugin.isBinary;
  68896. var database;
  68897. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  68898. var dataCallback = function (data, responseURL) {
  68899. if (scene.isDisposed) {
  68900. onError("Scene has been disposed");
  68901. return;
  68902. }
  68903. scene.database = database;
  68904. onSuccess(plugin, data, responseURL);
  68905. };
  68906. var request = null;
  68907. var pluginDisposed = false;
  68908. var onDisposeObservable = plugin.onDisposeObservable;
  68909. if (onDisposeObservable) {
  68910. onDisposeObservable.add(function () {
  68911. pluginDisposed = true;
  68912. if (request) {
  68913. request.abort();
  68914. request = null;
  68915. }
  68916. onDispose();
  68917. });
  68918. }
  68919. var manifestChecked = function () {
  68920. if (pluginDisposed) {
  68921. return;
  68922. }
  68923. var url = rootUrl + sceneFilename;
  68924. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  68925. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  68926. } : undefined, database, useArrayBuffer, function (request, exception) {
  68927. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  68928. });
  68929. };
  68930. if (directLoad) {
  68931. dataCallback(directLoad);
  68932. return plugin;
  68933. }
  68934. if (rootUrl.indexOf("file:") === -1) {
  68935. var engine = scene.getEngine();
  68936. var canUseOfflineSupport = engine.enableOfflineSupport;
  68937. if (canUseOfflineSupport) {
  68938. // Also check for exceptions
  68939. var exceptionFound = false;
  68940. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  68941. var regex = _a[_i];
  68942. if (regex.test(rootUrl + sceneFilename)) {
  68943. exceptionFound = true;
  68944. break;
  68945. }
  68946. }
  68947. canUseOfflineSupport = !exceptionFound;
  68948. }
  68949. if (canUseOfflineSupport) {
  68950. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  68951. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  68952. }
  68953. else {
  68954. manifestChecked();
  68955. }
  68956. }
  68957. // Loading file from disk via input file or drag'n'drop
  68958. else {
  68959. var fileOrString = sceneFilename;
  68960. if (fileOrString.name) { // File
  68961. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  68962. }
  68963. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  68964. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  68965. }
  68966. else {
  68967. onError("Unable to find file named " + sceneFilename);
  68968. }
  68969. }
  68970. return plugin;
  68971. };
  68972. // Public functions
  68973. SceneLoader.GetPluginForExtension = function (extension) {
  68974. return SceneLoader._getPluginForExtension(extension).plugin;
  68975. };
  68976. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  68977. return !!SceneLoader._registeredPlugins[extension];
  68978. };
  68979. SceneLoader.RegisterPlugin = function (plugin) {
  68980. if (typeof plugin.extensions === "string") {
  68981. var extension = plugin.extensions;
  68982. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  68983. plugin: plugin,
  68984. isBinary: false
  68985. };
  68986. }
  68987. else {
  68988. var extensions = plugin.extensions;
  68989. Object.keys(extensions).forEach(function (extension) {
  68990. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  68991. plugin: plugin,
  68992. isBinary: extensions[extension].isBinary
  68993. };
  68994. });
  68995. }
  68996. };
  68997. /**
  68998. * Import meshes into a scene
  68999. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69000. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69001. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69002. * @param scene the instance of BABYLON.Scene to append to
  69003. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  69004. * @param onProgress a callback with a progress event for each file being loaded
  69005. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69006. * @param pluginExtension the extension used to determine the plugin
  69007. * @returns The loaded plugin
  69008. */
  69009. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69010. if (sceneFilename === void 0) { sceneFilename = ""; }
  69011. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69012. if (onSuccess === void 0) { onSuccess = null; }
  69013. if (onProgress === void 0) { onProgress = null; }
  69014. if (onError === void 0) { onError = null; }
  69015. if (pluginExtension === void 0) { pluginExtension = null; }
  69016. if (!scene) {
  69017. BABYLON.Tools.Error("No scene available to import mesh to");
  69018. return null;
  69019. }
  69020. if (!sceneFilename) {
  69021. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69022. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69023. }
  69024. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69025. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69026. return null;
  69027. }
  69028. var loadingToken = {};
  69029. scene._addPendingData(loadingToken);
  69030. var disposeHandler = function () {
  69031. scene._removePendingData(loadingToken);
  69032. };
  69033. var errorHandler = function (message, exception) {
  69034. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  69035. if (onError) {
  69036. onError(scene, errorMessage, exception);
  69037. }
  69038. else {
  69039. BABYLON.Tools.Error(errorMessage);
  69040. // should the exception be thrown?
  69041. }
  69042. disposeHandler();
  69043. };
  69044. var progressHandler = onProgress ? function (event) {
  69045. try {
  69046. onProgress(event);
  69047. }
  69048. catch (e) {
  69049. errorHandler("Error in onProgress callback", e);
  69050. }
  69051. } : undefined;
  69052. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  69053. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  69054. if (onSuccess) {
  69055. try {
  69056. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  69057. }
  69058. catch (e) {
  69059. errorHandler("Error in onSuccess callback", e);
  69060. }
  69061. }
  69062. scene._removePendingData(loadingToken);
  69063. };
  69064. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69065. if (plugin.rewriteRootURL) {
  69066. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  69067. }
  69068. if (sceneFilename === "") {
  69069. if (sceneFilename === "") {
  69070. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69071. }
  69072. }
  69073. if (plugin.importMesh) {
  69074. var syncedPlugin = plugin;
  69075. var meshes = new Array();
  69076. var particleSystems = new Array();
  69077. var skeletons = new Array();
  69078. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  69079. return;
  69080. }
  69081. scene.loadingPluginName = plugin.name;
  69082. successHandler(meshes, particleSystems, skeletons, []);
  69083. }
  69084. else {
  69085. var asyncedPlugin = plugin;
  69086. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  69087. scene.loadingPluginName = plugin.name;
  69088. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  69089. }).catch(function (error) {
  69090. errorHandler(error.message, error);
  69091. });
  69092. }
  69093. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69094. };
  69095. /**
  69096. * Import meshes into a scene
  69097. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69098. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69099. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69100. * @param scene the instance of BABYLON.Scene to append to
  69101. * @param onProgress a callback with a progress event for each file being loaded
  69102. * @param pluginExtension the extension used to determine the plugin
  69103. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  69104. */
  69105. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69106. if (sceneFilename === void 0) { sceneFilename = ""; }
  69107. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69108. if (onProgress === void 0) { onProgress = null; }
  69109. if (pluginExtension === void 0) { pluginExtension = null; }
  69110. return new Promise(function (resolve, reject) {
  69111. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  69112. resolve({
  69113. meshes: meshes,
  69114. particleSystems: particleSystems,
  69115. skeletons: skeletons,
  69116. animationGroups: animationGroups
  69117. });
  69118. }, onProgress, function (scene, message, exception) {
  69119. reject(exception || new Error(message));
  69120. }, pluginExtension);
  69121. });
  69122. };
  69123. /**
  69124. * Load a scene
  69125. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69126. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69127. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69128. * @param onSuccess a callback with the scene when import succeeds
  69129. * @param onProgress a callback with a progress event for each file being loaded
  69130. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69131. * @param pluginExtension the extension used to determine the plugin
  69132. * @returns The loaded plugin
  69133. */
  69134. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  69135. if (onSuccess === void 0) { onSuccess = null; }
  69136. if (onProgress === void 0) { onProgress = null; }
  69137. if (onError === void 0) { onError = null; }
  69138. if (pluginExtension === void 0) { pluginExtension = null; }
  69139. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  69140. };
  69141. /**
  69142. * Load a scene
  69143. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69144. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69145. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69146. * @param onProgress a callback with a progress event for each file being loaded
  69147. * @param pluginExtension the extension used to determine the plugin
  69148. * @returns The loaded scene
  69149. */
  69150. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  69151. if (onProgress === void 0) { onProgress = null; }
  69152. if (pluginExtension === void 0) { pluginExtension = null; }
  69153. return new Promise(function (resolve, reject) {
  69154. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  69155. resolve(scene);
  69156. }, onProgress, function (scene, message, exception) {
  69157. reject(exception || new Error(message));
  69158. }, pluginExtension);
  69159. });
  69160. };
  69161. /**
  69162. * Append a scene
  69163. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69164. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69165. * @param scene is the instance of BABYLON.Scene to append to
  69166. * @param onSuccess a callback with the scene when import succeeds
  69167. * @param onProgress a callback with a progress event for each file being loaded
  69168. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69169. * @param pluginExtension the extension used to determine the plugin
  69170. * @returns The loaded plugin
  69171. */
  69172. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69173. if (sceneFilename === void 0) { sceneFilename = ""; }
  69174. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69175. if (onSuccess === void 0) { onSuccess = null; }
  69176. if (onProgress === void 0) { onProgress = null; }
  69177. if (onError === void 0) { onError = null; }
  69178. if (pluginExtension === void 0) { pluginExtension = null; }
  69179. if (!scene) {
  69180. BABYLON.Tools.Error("No scene available to append to");
  69181. return null;
  69182. }
  69183. if (!sceneFilename) {
  69184. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69185. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69186. }
  69187. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69188. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69189. return null;
  69190. }
  69191. if (SceneLoader.ShowLoadingScreen) {
  69192. scene.getEngine().displayLoadingUI();
  69193. }
  69194. var loadingToken = {};
  69195. scene._addPendingData(loadingToken);
  69196. var disposeHandler = function () {
  69197. scene._removePendingData(loadingToken);
  69198. scene.getEngine().hideLoadingUI();
  69199. };
  69200. var errorHandler = function (message, exception) {
  69201. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69202. if (onError) {
  69203. onError(scene, errorMessage, exception);
  69204. }
  69205. else {
  69206. BABYLON.Tools.Error(errorMessage);
  69207. // should the exception be thrown?
  69208. }
  69209. disposeHandler();
  69210. };
  69211. var progressHandler = onProgress ? function (event) {
  69212. try {
  69213. onProgress(event);
  69214. }
  69215. catch (e) {
  69216. errorHandler("Error in onProgress callback", e);
  69217. }
  69218. } : undefined;
  69219. var successHandler = function () {
  69220. if (onSuccess) {
  69221. try {
  69222. onSuccess(scene);
  69223. }
  69224. catch (e) {
  69225. errorHandler("Error in onSuccess callback", e);
  69226. }
  69227. }
  69228. scene._removePendingData(loadingToken);
  69229. };
  69230. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69231. if (sceneFilename === "") {
  69232. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69233. }
  69234. if (plugin.load) {
  69235. var syncedPlugin = plugin;
  69236. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  69237. return;
  69238. }
  69239. scene.loadingPluginName = plugin.name;
  69240. successHandler();
  69241. }
  69242. else {
  69243. var asyncedPlugin = plugin;
  69244. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  69245. scene.loadingPluginName = plugin.name;
  69246. successHandler();
  69247. }).catch(function (error) {
  69248. errorHandler(error.message, error);
  69249. });
  69250. }
  69251. if (SceneLoader.ShowLoadingScreen) {
  69252. scene.executeWhenReady(function () {
  69253. scene.getEngine().hideLoadingUI();
  69254. });
  69255. }
  69256. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69257. };
  69258. /**
  69259. * Append a scene
  69260. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69261. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69262. * @param scene is the instance of BABYLON.Scene to append to
  69263. * @param onProgress a callback with a progress event for each file being loaded
  69264. * @param pluginExtension the extension used to determine the plugin
  69265. * @returns The given scene
  69266. */
  69267. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69268. if (sceneFilename === void 0) { sceneFilename = ""; }
  69269. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69270. if (onProgress === void 0) { onProgress = null; }
  69271. if (pluginExtension === void 0) { pluginExtension = null; }
  69272. return new Promise(function (resolve, reject) {
  69273. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  69274. resolve(scene);
  69275. }, onProgress, function (scene, message, exception) {
  69276. reject(exception || new Error(message));
  69277. }, pluginExtension);
  69278. });
  69279. };
  69280. /**
  69281. * Load a scene into an asset container
  69282. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69283. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69284. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  69285. * @param onSuccess a callback with the scene when import succeeds
  69286. * @param onProgress a callback with a progress event for each file being loaded
  69287. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69288. * @param pluginExtension the extension used to determine the plugin
  69289. * @returns The loaded plugin
  69290. */
  69291. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69292. if (sceneFilename === void 0) { sceneFilename = ""; }
  69293. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69294. if (onSuccess === void 0) { onSuccess = null; }
  69295. if (onProgress === void 0) { onProgress = null; }
  69296. if (onError === void 0) { onError = null; }
  69297. if (pluginExtension === void 0) { pluginExtension = null; }
  69298. if (!scene) {
  69299. BABYLON.Tools.Error("No scene available to load asset container to");
  69300. return null;
  69301. }
  69302. if (!sceneFilename) {
  69303. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69304. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69305. }
  69306. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69307. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69308. return null;
  69309. }
  69310. var loadingToken = {};
  69311. scene._addPendingData(loadingToken);
  69312. var disposeHandler = function () {
  69313. scene._removePendingData(loadingToken);
  69314. };
  69315. var errorHandler = function (message, exception) {
  69316. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69317. if (onError) {
  69318. onError(scene, errorMessage, exception);
  69319. }
  69320. else {
  69321. BABYLON.Tools.Error(errorMessage);
  69322. // should the exception be thrown?
  69323. }
  69324. disposeHandler();
  69325. };
  69326. var progressHandler = onProgress ? function (event) {
  69327. try {
  69328. onProgress(event);
  69329. }
  69330. catch (e) {
  69331. errorHandler("Error in onProgress callback", e);
  69332. }
  69333. } : undefined;
  69334. var successHandler = function (assets) {
  69335. if (onSuccess) {
  69336. try {
  69337. onSuccess(assets);
  69338. }
  69339. catch (e) {
  69340. errorHandler("Error in onSuccess callback", e);
  69341. }
  69342. }
  69343. scene._removePendingData(loadingToken);
  69344. };
  69345. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69346. if (plugin.loadAssetContainer) {
  69347. var syncedPlugin = plugin;
  69348. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  69349. if (!assetContainer) {
  69350. return;
  69351. }
  69352. scene.loadingPluginName = plugin.name;
  69353. successHandler(assetContainer);
  69354. }
  69355. else if (plugin.loadAssetContainerAsync) {
  69356. var asyncedPlugin = plugin;
  69357. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  69358. scene.loadingPluginName = plugin.name;
  69359. successHandler(assetContainer);
  69360. }).catch(function (error) {
  69361. errorHandler(error.message, error);
  69362. });
  69363. }
  69364. else {
  69365. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  69366. }
  69367. if (SceneLoader.ShowLoadingScreen) {
  69368. scene.executeWhenReady(function () {
  69369. scene.getEngine().hideLoadingUI();
  69370. });
  69371. }
  69372. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69373. };
  69374. /**
  69375. * Load a scene into an asset container
  69376. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69377. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69378. * @param scene is the instance of BABYLON.Scene to append to
  69379. * @param onProgress a callback with a progress event for each file being loaded
  69380. * @param pluginExtension the extension used to determine the plugin
  69381. * @returns The loaded asset container
  69382. */
  69383. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69384. if (sceneFilename === void 0) { sceneFilename = ""; }
  69385. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69386. if (onProgress === void 0) { onProgress = null; }
  69387. if (pluginExtension === void 0) { pluginExtension = null; }
  69388. return new Promise(function (resolve, reject) {
  69389. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  69390. resolve(assetContainer);
  69391. }, onProgress, function (scene, message, exception) {
  69392. reject(exception || new Error(message));
  69393. }, pluginExtension);
  69394. });
  69395. };
  69396. // Flags
  69397. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  69398. SceneLoader._ShowLoadingScreen = true;
  69399. SceneLoader._CleanBoneMatrixWeights = false;
  69400. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  69401. // Members
  69402. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  69403. SceneLoader._registeredPlugins = {};
  69404. return SceneLoader;
  69405. }());
  69406. BABYLON.SceneLoader = SceneLoader;
  69407. ;
  69408. })(BABYLON || (BABYLON = {}));
  69409. //# sourceMappingURL=babylon.sceneLoader.js.map
  69410. var BABYLON;
  69411. (function (BABYLON) {
  69412. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  69413. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69414. var parsedMaterial = parsedData.materials[index];
  69415. if (parsedMaterial.id === id) {
  69416. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69417. }
  69418. }
  69419. return null;
  69420. };
  69421. var isDescendantOf = function (mesh, names, hierarchyIds) {
  69422. for (var i in names) {
  69423. if (mesh.name === names[i]) {
  69424. hierarchyIds.push(mesh.id);
  69425. return true;
  69426. }
  69427. }
  69428. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  69429. hierarchyIds.push(mesh.id);
  69430. return true;
  69431. }
  69432. return false;
  69433. };
  69434. var logOperation = function (operation, producer) {
  69435. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  69436. };
  69437. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  69438. if (addToScene === void 0) { addToScene = false; }
  69439. var container = new BABYLON.AssetContainer(scene);
  69440. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69441. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69442. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69443. // and avoid problems with multiple concurrent .babylon loads.
  69444. var log = "importScene has failed JSON parse";
  69445. try {
  69446. var parsedData = JSON.parse(data);
  69447. log = "";
  69448. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69449. var index;
  69450. var cache;
  69451. // Lights
  69452. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  69453. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  69454. var parsedLight = parsedData.lights[index];
  69455. var light = BABYLON.Light.Parse(parsedLight, scene);
  69456. if (light) {
  69457. container.lights.push(light);
  69458. log += (index === 0 ? "\n\tLights:" : "");
  69459. log += "\n\t\t" + light.toString(fullDetails);
  69460. }
  69461. }
  69462. }
  69463. // Animations
  69464. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  69465. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  69466. var parsedAnimation = parsedData.animations[index];
  69467. var animation = BABYLON.Animation.Parse(parsedAnimation);
  69468. scene.animations.push(animation);
  69469. container.animations.push(animation);
  69470. log += (index === 0 ? "\n\tAnimations:" : "");
  69471. log += "\n\t\t" + animation.toString(fullDetails);
  69472. }
  69473. }
  69474. // Materials
  69475. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  69476. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69477. var parsedMaterial = parsedData.materials[index];
  69478. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69479. container.materials.push(mat);
  69480. log += (index === 0 ? "\n\tMaterials:" : "");
  69481. log += "\n\t\t" + mat.toString(fullDetails);
  69482. }
  69483. }
  69484. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69485. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  69486. var parsedMultiMaterial = parsedData.multiMaterials[index];
  69487. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69488. container.multiMaterials.push(mmat);
  69489. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  69490. log += "\n\t\t" + mmat.toString(fullDetails);
  69491. }
  69492. }
  69493. // Morph targets
  69494. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69495. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69496. var managerData = _a[_i];
  69497. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  69498. }
  69499. }
  69500. // Skeletons
  69501. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69502. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  69503. var parsedSkeleton = parsedData.skeletons[index];
  69504. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  69505. container.skeletons.push(skeleton);
  69506. log += (index === 0 ? "\n\tSkeletons:" : "");
  69507. log += "\n\t\t" + skeleton.toString(fullDetails);
  69508. }
  69509. }
  69510. // Geometries
  69511. var geometries = parsedData.geometries;
  69512. if (geometries !== undefined && geometries !== null) {
  69513. var addedGeometry = new Array();
  69514. // Boxes
  69515. var boxes = geometries.boxes;
  69516. if (boxes !== undefined && boxes !== null) {
  69517. for (index = 0, cache = boxes.length; index < cache; index++) {
  69518. var parsedBox = boxes[index];
  69519. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  69520. }
  69521. }
  69522. // Spheres
  69523. var spheres = geometries.spheres;
  69524. if (spheres !== undefined && spheres !== null) {
  69525. for (index = 0, cache = spheres.length; index < cache; index++) {
  69526. var parsedSphere = spheres[index];
  69527. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  69528. }
  69529. }
  69530. // Cylinders
  69531. var cylinders = geometries.cylinders;
  69532. if (cylinders !== undefined && cylinders !== null) {
  69533. for (index = 0, cache = cylinders.length; index < cache; index++) {
  69534. var parsedCylinder = cylinders[index];
  69535. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  69536. }
  69537. }
  69538. // Toruses
  69539. var toruses = geometries.toruses;
  69540. if (toruses !== undefined && toruses !== null) {
  69541. for (index = 0, cache = toruses.length; index < cache; index++) {
  69542. var parsedTorus = toruses[index];
  69543. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  69544. }
  69545. }
  69546. // Grounds
  69547. var grounds = geometries.grounds;
  69548. if (grounds !== undefined && grounds !== null) {
  69549. for (index = 0, cache = grounds.length; index < cache; index++) {
  69550. var parsedGround = grounds[index];
  69551. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  69552. }
  69553. }
  69554. // Planes
  69555. var planes = geometries.planes;
  69556. if (planes !== undefined && planes !== null) {
  69557. for (index = 0, cache = planes.length; index < cache; index++) {
  69558. var parsedPlane = planes[index];
  69559. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  69560. }
  69561. }
  69562. // TorusKnots
  69563. var torusKnots = geometries.torusKnots;
  69564. if (torusKnots !== undefined && torusKnots !== null) {
  69565. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  69566. var parsedTorusKnot = torusKnots[index];
  69567. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  69568. }
  69569. }
  69570. // VertexData
  69571. var vertexData = geometries.vertexData;
  69572. if (vertexData !== undefined && vertexData !== null) {
  69573. for (index = 0, cache = vertexData.length; index < cache; index++) {
  69574. var parsedVertexData = vertexData[index];
  69575. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  69576. }
  69577. }
  69578. addedGeometry.forEach(function (g) {
  69579. if (g) {
  69580. container.geometries.push(g);
  69581. }
  69582. });
  69583. }
  69584. // Transform nodes
  69585. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  69586. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  69587. var parsedTransformNode = parsedData.transformNodes[index];
  69588. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  69589. container.transformNodes.push(node);
  69590. }
  69591. }
  69592. // Meshes
  69593. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69594. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69595. var parsedMesh = parsedData.meshes[index];
  69596. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  69597. container.meshes.push(mesh);
  69598. log += (index === 0 ? "\n\tMeshes:" : "");
  69599. log += "\n\t\t" + mesh.toString(fullDetails);
  69600. }
  69601. }
  69602. // Cameras
  69603. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  69604. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  69605. var parsedCamera = parsedData.cameras[index];
  69606. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  69607. container.cameras.push(camera);
  69608. log += (index === 0 ? "\n\tCameras:" : "");
  69609. log += "\n\t\t" + camera.toString(fullDetails);
  69610. }
  69611. }
  69612. // Browsing all the graph to connect the dots
  69613. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  69614. var camera = scene.cameras[index];
  69615. if (camera._waitingParentId) {
  69616. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  69617. camera._waitingParentId = null;
  69618. }
  69619. }
  69620. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69621. var light_1 = scene.lights[index];
  69622. if (light_1 && light_1._waitingParentId) {
  69623. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  69624. light_1._waitingParentId = null;
  69625. }
  69626. }
  69627. // Sounds
  69628. // TODO: add sound
  69629. var loadedSounds = [];
  69630. var loadedSound;
  69631. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  69632. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  69633. var parsedSound = parsedData.sounds[index];
  69634. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69635. if (!parsedSound.url)
  69636. parsedSound.url = parsedSound.name;
  69637. if (!loadedSounds[parsedSound.url]) {
  69638. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  69639. loadedSounds[parsedSound.url] = loadedSound;
  69640. container.sounds.push(loadedSound);
  69641. }
  69642. else {
  69643. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  69644. }
  69645. }
  69646. else {
  69647. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  69648. }
  69649. }
  69650. }
  69651. loadedSounds = [];
  69652. // Connect parents & children and parse actions
  69653. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  69654. var transformNode = scene.transformNodes[index];
  69655. if (transformNode._waitingParentId) {
  69656. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  69657. transformNode._waitingParentId = null;
  69658. }
  69659. }
  69660. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69661. var mesh = scene.meshes[index];
  69662. if (mesh._waitingParentId) {
  69663. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  69664. mesh._waitingParentId = null;
  69665. }
  69666. if (mesh._waitingActions) {
  69667. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  69668. mesh._waitingActions = null;
  69669. }
  69670. }
  69671. // freeze world matrix application
  69672. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69673. var currentMesh = scene.meshes[index];
  69674. if (currentMesh._waitingFreezeWorldMatrix) {
  69675. currentMesh.freezeWorldMatrix();
  69676. currentMesh._waitingFreezeWorldMatrix = null;
  69677. }
  69678. else {
  69679. currentMesh.computeWorldMatrix(true);
  69680. }
  69681. }
  69682. // Shadows
  69683. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  69684. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  69685. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  69686. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  69687. // SG would be available on their associated lights
  69688. }
  69689. }
  69690. // Lights exclusions / inclusions
  69691. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69692. var light_2 = scene.lights[index];
  69693. // Excluded check
  69694. if (light_2._excludedMeshesIds.length > 0) {
  69695. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  69696. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  69697. if (excludedMesh) {
  69698. light_2.excludedMeshes.push(excludedMesh);
  69699. }
  69700. }
  69701. light_2._excludedMeshesIds = [];
  69702. }
  69703. // Included check
  69704. if (light_2._includedOnlyMeshesIds.length > 0) {
  69705. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  69706. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  69707. if (includedOnlyMesh) {
  69708. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  69709. }
  69710. }
  69711. light_2._includedOnlyMeshesIds = [];
  69712. }
  69713. }
  69714. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  69715. // Actions (scene)
  69716. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  69717. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  69718. }
  69719. if (!addToScene) {
  69720. container.removeAllFromScene();
  69721. }
  69722. }
  69723. catch (err) {
  69724. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  69725. if (onError) {
  69726. onError(msg, err);
  69727. }
  69728. else {
  69729. BABYLON.Tools.Log(msg);
  69730. throw err;
  69731. }
  69732. }
  69733. finally {
  69734. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69735. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69736. }
  69737. }
  69738. return container;
  69739. };
  69740. BABYLON.SceneLoader.RegisterPlugin({
  69741. name: "babylon.js",
  69742. extensions: ".babylon",
  69743. canDirectLoad: function (data) {
  69744. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  69745. return true;
  69746. }
  69747. return false;
  69748. },
  69749. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  69750. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69751. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69752. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69753. // and avoid problems with multiple concurrent .babylon loads.
  69754. var log = "importMesh has failed JSON parse";
  69755. try {
  69756. var parsedData = JSON.parse(data);
  69757. log = "";
  69758. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69759. if (!meshesNames) {
  69760. meshesNames = null;
  69761. }
  69762. else if (!Array.isArray(meshesNames)) {
  69763. meshesNames = [meshesNames];
  69764. }
  69765. var hierarchyIds = new Array();
  69766. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69767. var loadedSkeletonsIds = [];
  69768. var loadedMaterialsIds = [];
  69769. var index;
  69770. var cache;
  69771. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69772. var parsedMesh = parsedData.meshes[index];
  69773. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  69774. if (meshesNames !== null) {
  69775. // Remove found mesh name from list.
  69776. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  69777. }
  69778. //Geometry?
  69779. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  69780. //does the file contain geometries?
  69781. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  69782. //find the correct geometry and add it to the scene
  69783. var found = false;
  69784. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  69785. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  69786. return;
  69787. }
  69788. else {
  69789. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  69790. if (parsedGeometryData.id === parsedMesh.geometryId) {
  69791. switch (geometryType) {
  69792. case "boxes":
  69793. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  69794. break;
  69795. case "spheres":
  69796. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  69797. break;
  69798. case "cylinders":
  69799. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  69800. break;
  69801. case "toruses":
  69802. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  69803. break;
  69804. case "grounds":
  69805. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  69806. break;
  69807. case "planes":
  69808. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  69809. break;
  69810. case "torusKnots":
  69811. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  69812. break;
  69813. case "vertexData":
  69814. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  69815. break;
  69816. }
  69817. found = true;
  69818. }
  69819. });
  69820. }
  69821. });
  69822. if (found === false) {
  69823. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  69824. }
  69825. }
  69826. }
  69827. // Material ?
  69828. if (parsedMesh.materialId) {
  69829. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  69830. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69831. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  69832. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  69833. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  69834. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  69835. var subMatId = parsedMultiMaterial.materials[matIndex];
  69836. loadedMaterialsIds.push(subMatId);
  69837. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  69838. if (mat) {
  69839. log += "\n\tMaterial " + mat.toString(fullDetails);
  69840. }
  69841. }
  69842. loadedMaterialsIds.push(parsedMultiMaterial.id);
  69843. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69844. if (mmat) {
  69845. materialFound = true;
  69846. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  69847. }
  69848. break;
  69849. }
  69850. }
  69851. }
  69852. if (materialFound === false) {
  69853. loadedMaterialsIds.push(parsedMesh.materialId);
  69854. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  69855. if (!mat) {
  69856. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  69857. }
  69858. else {
  69859. log += "\n\tMaterial " + mat.toString(fullDetails);
  69860. }
  69861. }
  69862. }
  69863. // Skeleton ?
  69864. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69865. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  69866. if (skeletonAlreadyLoaded === false) {
  69867. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  69868. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  69869. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  69870. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  69871. skeletons.push(skeleton);
  69872. loadedSkeletonsIds.push(parsedSkeleton.id);
  69873. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  69874. }
  69875. }
  69876. }
  69877. }
  69878. // Morph targets ?
  69879. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69880. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69881. var managerData = _a[_i];
  69882. BABYLON.MorphTargetManager.Parse(managerData, scene);
  69883. }
  69884. }
  69885. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  69886. meshes.push(mesh);
  69887. log += "\n\tMesh " + mesh.toString(fullDetails);
  69888. }
  69889. }
  69890. // Connecting parents
  69891. var currentMesh;
  69892. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69893. currentMesh = scene.meshes[index];
  69894. if (currentMesh._waitingParentId) {
  69895. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  69896. currentMesh._waitingParentId = null;
  69897. }
  69898. }
  69899. // freeze and compute world matrix application
  69900. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69901. currentMesh = scene.meshes[index];
  69902. if (currentMesh._waitingFreezeWorldMatrix) {
  69903. currentMesh.freezeWorldMatrix();
  69904. currentMesh._waitingFreezeWorldMatrix = null;
  69905. }
  69906. else {
  69907. currentMesh.computeWorldMatrix(true);
  69908. }
  69909. }
  69910. }
  69911. // Particles
  69912. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  69913. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  69914. if (parser) {
  69915. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  69916. var parsedParticleSystem = parsedData.particleSystems[index];
  69917. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  69918. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  69919. }
  69920. }
  69921. }
  69922. }
  69923. return true;
  69924. }
  69925. catch (err) {
  69926. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  69927. if (onError) {
  69928. onError(msg, err);
  69929. }
  69930. else {
  69931. BABYLON.Tools.Log(msg);
  69932. throw err;
  69933. }
  69934. }
  69935. finally {
  69936. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69937. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69938. }
  69939. }
  69940. return false;
  69941. },
  69942. load: function (scene, data, rootUrl, onError) {
  69943. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69944. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69945. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69946. // and avoid problems with multiple concurrent .babylon loads.
  69947. var log = "importScene has failed JSON parse";
  69948. try {
  69949. var parsedData = JSON.parse(data);
  69950. log = "";
  69951. // Scene
  69952. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  69953. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  69954. }
  69955. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  69956. scene.autoClear = parsedData.autoClear;
  69957. }
  69958. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  69959. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  69960. }
  69961. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  69962. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  69963. }
  69964. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  69965. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  69966. }
  69967. // Fog
  69968. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  69969. scene.fogMode = parsedData.fogMode;
  69970. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  69971. scene.fogStart = parsedData.fogStart;
  69972. scene.fogEnd = parsedData.fogEnd;
  69973. scene.fogDensity = parsedData.fogDensity;
  69974. log += "\tFog mode for scene: ";
  69975. switch (scene.fogMode) {
  69976. // getters not compiling, so using hardcoded
  69977. case 1:
  69978. log += "exp\n";
  69979. break;
  69980. case 2:
  69981. log += "exp2\n";
  69982. break;
  69983. case 3:
  69984. log += "linear\n";
  69985. break;
  69986. }
  69987. }
  69988. //Physics
  69989. if (parsedData.physicsEnabled) {
  69990. var physicsPlugin;
  69991. if (parsedData.physicsEngine === "cannon") {
  69992. physicsPlugin = new BABYLON.CannonJSPlugin();
  69993. }
  69994. else if (parsedData.physicsEngine === "oimo") {
  69995. physicsPlugin = new BABYLON.OimoJSPlugin();
  69996. }
  69997. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  69998. //else - default engine, which is currently oimo
  69999. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  70000. scene.enablePhysics(physicsGravity, physicsPlugin);
  70001. }
  70002. // Metadata
  70003. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  70004. scene.metadata = parsedData.metadata;
  70005. }
  70006. //collisions, if defined. otherwise, default is true
  70007. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  70008. scene.collisionsEnabled = parsedData.collisionsEnabled;
  70009. }
  70010. scene.workerCollisions = !!parsedData.workerCollisions;
  70011. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  70012. if (!container) {
  70013. return false;
  70014. }
  70015. if (parsedData.autoAnimate) {
  70016. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  70017. }
  70018. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  70019. scene.setActiveCameraByID(parsedData.activeCameraID);
  70020. }
  70021. // Environment texture
  70022. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  70023. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  70024. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  70025. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  70026. if (parsedData.environmentTextureRotationY) {
  70027. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  70028. }
  70029. scene.environmentTexture = hdrTexture;
  70030. }
  70031. else {
  70032. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  70033. if (parsedData.environmentTextureRotationY) {
  70034. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  70035. }
  70036. scene.environmentTexture = cubeTexture;
  70037. }
  70038. if (parsedData.createDefaultSkybox === true) {
  70039. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  70040. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  70041. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  70042. }
  70043. }
  70044. // Finish
  70045. return true;
  70046. }
  70047. catch (err) {
  70048. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  70049. if (onError) {
  70050. onError(msg, err);
  70051. }
  70052. else {
  70053. BABYLON.Tools.Log(msg);
  70054. throw err;
  70055. }
  70056. }
  70057. finally {
  70058. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70059. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70060. }
  70061. }
  70062. return false;
  70063. },
  70064. loadAssetContainer: function (scene, data, rootUrl, onError) {
  70065. var container = loadAssetContainer(scene, data, rootUrl, onError);
  70066. return container;
  70067. }
  70068. });
  70069. })(BABYLON || (BABYLON = {}));
  70070. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  70071. var BABYLON;
  70072. (function (BABYLON) {
  70073. var FilesInput = /** @class */ (function () {
  70074. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  70075. this.onProcessFileCallback = function () { return true; };
  70076. this._engine = engine;
  70077. this._currentScene = scene;
  70078. this._sceneLoadedCallback = sceneLoadedCallback;
  70079. this._progressCallback = progressCallback;
  70080. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  70081. this._textureLoadingCallback = textureLoadingCallback;
  70082. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  70083. this._onReloadCallback = onReloadCallback;
  70084. this._errorCallback = errorCallback;
  70085. }
  70086. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  70087. var _this = this;
  70088. if (elementToMonitor) {
  70089. this._elementToMonitor = elementToMonitor;
  70090. this._dragEnterHandler = function (e) { _this.drag(e); };
  70091. this._dragOverHandler = function (e) { _this.drag(e); };
  70092. this._dropHandler = function (e) { _this.drop(e); };
  70093. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  70094. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  70095. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  70096. }
  70097. };
  70098. FilesInput.prototype.dispose = function () {
  70099. if (!this._elementToMonitor) {
  70100. return;
  70101. }
  70102. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  70103. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  70104. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  70105. };
  70106. FilesInput.prototype.renderFunction = function () {
  70107. if (this._additionalRenderLoopLogicCallback) {
  70108. this._additionalRenderLoopLogicCallback();
  70109. }
  70110. if (this._currentScene) {
  70111. if (this._textureLoadingCallback) {
  70112. var remaining = this._currentScene.getWaitingItemsCount();
  70113. if (remaining > 0) {
  70114. this._textureLoadingCallback(remaining);
  70115. }
  70116. }
  70117. this._currentScene.render();
  70118. }
  70119. };
  70120. FilesInput.prototype.drag = function (e) {
  70121. e.stopPropagation();
  70122. e.preventDefault();
  70123. };
  70124. FilesInput.prototype.drop = function (eventDrop) {
  70125. eventDrop.stopPropagation();
  70126. eventDrop.preventDefault();
  70127. this.loadFiles(eventDrop);
  70128. };
  70129. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  70130. var _this = this;
  70131. var reader = folder.createReader();
  70132. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  70133. reader.readEntries(function (entries) {
  70134. remaining.count += entries.length;
  70135. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  70136. var entry = entries_1[_i];
  70137. if (entry.isFile) {
  70138. entry.file(function (file) {
  70139. file.correctName = relativePath + file.name;
  70140. files.push(file);
  70141. if (--remaining.count === 0) {
  70142. callback();
  70143. }
  70144. });
  70145. }
  70146. else if (entry.isDirectory) {
  70147. _this._traverseFolder(entry, files, remaining, callback);
  70148. }
  70149. }
  70150. if (--remaining.count) {
  70151. callback();
  70152. }
  70153. });
  70154. };
  70155. FilesInput.prototype._processFiles = function (files) {
  70156. for (var i = 0; i < files.length; i++) {
  70157. var name = files[i].correctName.toLowerCase();
  70158. var extension = name.split('.').pop();
  70159. if (!this.onProcessFileCallback(files[i], name, extension)) {
  70160. continue;
  70161. }
  70162. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  70163. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  70164. this._sceneFileToLoad = files[i];
  70165. }
  70166. else {
  70167. FilesInput.FilesToLoad[name] = files[i];
  70168. }
  70169. }
  70170. };
  70171. FilesInput.prototype.loadFiles = function (event) {
  70172. var _this = this;
  70173. if (this._startingProcessingFilesCallback)
  70174. this._startingProcessingFilesCallback();
  70175. // Handling data transfer via drag'n'drop
  70176. if (event && event.dataTransfer && event.dataTransfer.files) {
  70177. this._filesToLoad = event.dataTransfer.files;
  70178. }
  70179. // Handling files from input files
  70180. if (event && event.target && event.target.files) {
  70181. this._filesToLoad = event.target.files;
  70182. }
  70183. if (this._filesToLoad && this._filesToLoad.length > 0) {
  70184. var files_1 = new Array();
  70185. var folders = [];
  70186. var items = event.dataTransfer ? event.dataTransfer.items : null;
  70187. for (var i = 0; i < this._filesToLoad.length; i++) {
  70188. var fileToLoad = this._filesToLoad[i];
  70189. var name_1 = fileToLoad.name.toLowerCase();
  70190. var entry = void 0;
  70191. fileToLoad.correctName = name_1;
  70192. if (items) {
  70193. var item = items[i];
  70194. if (item.getAsEntry) {
  70195. entry = item.getAsEntry();
  70196. }
  70197. else if (item.webkitGetAsEntry) {
  70198. entry = item.webkitGetAsEntry();
  70199. }
  70200. }
  70201. if (!entry) {
  70202. files_1.push(fileToLoad);
  70203. }
  70204. else {
  70205. if (entry.isDirectory) {
  70206. folders.push(entry);
  70207. }
  70208. else {
  70209. files_1.push(fileToLoad);
  70210. }
  70211. }
  70212. }
  70213. if (folders.length === 0) {
  70214. this._processFiles(files_1);
  70215. this._processReload();
  70216. }
  70217. else {
  70218. var remaining = { count: folders.length };
  70219. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  70220. var folder = folders_1[_i];
  70221. this._traverseFolder(folder, files_1, remaining, function () {
  70222. _this._processFiles(files_1);
  70223. if (remaining.count === 0) {
  70224. _this._processReload();
  70225. }
  70226. });
  70227. }
  70228. }
  70229. }
  70230. };
  70231. FilesInput.prototype._processReload = function () {
  70232. if (this._onReloadCallback) {
  70233. this._onReloadCallback(this._sceneFileToLoad);
  70234. }
  70235. else {
  70236. this.reload();
  70237. }
  70238. };
  70239. FilesInput.prototype.reload = function () {
  70240. var _this = this;
  70241. // If a scene file has been provided
  70242. if (this._sceneFileToLoad) {
  70243. if (this._currentScene) {
  70244. if (BABYLON.Tools.errorsCount > 0) {
  70245. BABYLON.Tools.ClearLogCache();
  70246. }
  70247. this._engine.stopRenderLoop();
  70248. }
  70249. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  70250. if (_this._progressCallback) {
  70251. _this._progressCallback(progress);
  70252. }
  70253. }).then(function (scene) {
  70254. if (_this._currentScene) {
  70255. _this._currentScene.dispose();
  70256. }
  70257. _this._currentScene = scene;
  70258. if (_this._sceneLoadedCallback) {
  70259. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  70260. }
  70261. // Wait for textures and shaders to be ready
  70262. _this._currentScene.executeWhenReady(function () {
  70263. _this._engine.runRenderLoop(function () {
  70264. _this.renderFunction();
  70265. });
  70266. });
  70267. }).catch(function (error) {
  70268. if (_this._errorCallback) {
  70269. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  70270. }
  70271. });
  70272. }
  70273. else {
  70274. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  70275. }
  70276. };
  70277. FilesInput.FilesToLoad = {};
  70278. return FilesInput;
  70279. }());
  70280. BABYLON.FilesInput = FilesInput;
  70281. })(BABYLON || (BABYLON = {}));
  70282. //# sourceMappingURL=babylon.filesInput.js.map
  70283. var BABYLON;
  70284. (function (BABYLON) {
  70285. var Tags = /** @class */ (function () {
  70286. function Tags() {
  70287. }
  70288. Tags.EnableFor = function (obj) {
  70289. obj._tags = obj._tags || {};
  70290. obj.hasTags = function () {
  70291. return Tags.HasTags(obj);
  70292. };
  70293. obj.addTags = function (tagsString) {
  70294. return Tags.AddTagsTo(obj, tagsString);
  70295. };
  70296. obj.removeTags = function (tagsString) {
  70297. return Tags.RemoveTagsFrom(obj, tagsString);
  70298. };
  70299. obj.matchesTagsQuery = function (tagsQuery) {
  70300. return Tags.MatchesQuery(obj, tagsQuery);
  70301. };
  70302. };
  70303. Tags.DisableFor = function (obj) {
  70304. delete obj._tags;
  70305. delete obj.hasTags;
  70306. delete obj.addTags;
  70307. delete obj.removeTags;
  70308. delete obj.matchesTagsQuery;
  70309. };
  70310. Tags.HasTags = function (obj) {
  70311. if (!obj._tags) {
  70312. return false;
  70313. }
  70314. return !BABYLON.Tools.IsEmpty(obj._tags);
  70315. };
  70316. Tags.GetTags = function (obj, asString) {
  70317. if (asString === void 0) { asString = true; }
  70318. if (!obj._tags) {
  70319. return null;
  70320. }
  70321. if (asString) {
  70322. var tagsArray = [];
  70323. for (var tag in obj._tags) {
  70324. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  70325. tagsArray.push(tag);
  70326. }
  70327. }
  70328. return tagsArray.join(" ");
  70329. }
  70330. else {
  70331. return obj._tags;
  70332. }
  70333. };
  70334. // the tags 'true' and 'false' are reserved and cannot be used as tags
  70335. // a tag cannot start with '||', '&&', and '!'
  70336. // it cannot contain whitespaces
  70337. Tags.AddTagsTo = function (obj, tagsString) {
  70338. if (!tagsString) {
  70339. return;
  70340. }
  70341. if (typeof tagsString !== "string") {
  70342. return;
  70343. }
  70344. var tags = tagsString.split(" ");
  70345. tags.forEach(function (tag, index, array) {
  70346. Tags._AddTagTo(obj, tag);
  70347. });
  70348. };
  70349. Tags._AddTagTo = function (obj, tag) {
  70350. tag = tag.trim();
  70351. if (tag === "" || tag === "true" || tag === "false") {
  70352. return;
  70353. }
  70354. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  70355. return;
  70356. }
  70357. Tags.EnableFor(obj);
  70358. obj._tags[tag] = true;
  70359. };
  70360. Tags.RemoveTagsFrom = function (obj, tagsString) {
  70361. if (!Tags.HasTags(obj)) {
  70362. return;
  70363. }
  70364. var tags = tagsString.split(" ");
  70365. for (var t in tags) {
  70366. Tags._RemoveTagFrom(obj, tags[t]);
  70367. }
  70368. };
  70369. Tags._RemoveTagFrom = function (obj, tag) {
  70370. delete obj._tags[tag];
  70371. };
  70372. Tags.MatchesQuery = function (obj, tagsQuery) {
  70373. if (tagsQuery === undefined) {
  70374. return true;
  70375. }
  70376. if (tagsQuery === "") {
  70377. return Tags.HasTags(obj);
  70378. }
  70379. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  70380. };
  70381. return Tags;
  70382. }());
  70383. BABYLON.Tags = Tags;
  70384. })(BABYLON || (BABYLON = {}));
  70385. //# sourceMappingURL=babylon.tags.js.map
  70386. var BABYLON;
  70387. (function (BABYLON) {
  70388. /**
  70389. * Class used to evalaute queries containing `and` and `or` operators
  70390. */
  70391. var AndOrNotEvaluator = /** @class */ (function () {
  70392. function AndOrNotEvaluator() {
  70393. }
  70394. /**
  70395. * Evaluate a query
  70396. * @param query defines the query to evaluate
  70397. * @param evaluateCallback defines the callback used to filter result
  70398. * @returns true if the query matches
  70399. */
  70400. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  70401. if (!query.match(/\([^\(\)]*\)/g)) {
  70402. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  70403. }
  70404. else {
  70405. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  70406. // remove parenthesis
  70407. r = r.slice(1, r.length - 1);
  70408. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  70409. });
  70410. }
  70411. if (query === "true") {
  70412. return true;
  70413. }
  70414. if (query === "false") {
  70415. return false;
  70416. }
  70417. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  70418. };
  70419. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  70420. evaluateCallback = evaluateCallback || (function (r) {
  70421. return r === "true" ? true : false;
  70422. });
  70423. var result;
  70424. var or = parenthesisContent.split("||");
  70425. for (var i in or) {
  70426. if (or.hasOwnProperty(i)) {
  70427. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  70428. var and = ori.split("&&");
  70429. if (and.length > 1) {
  70430. for (var j = 0; j < and.length; ++j) {
  70431. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  70432. if (andj !== "true" && andj !== "false") {
  70433. if (andj[0] === "!") {
  70434. result = !evaluateCallback(andj.substring(1));
  70435. }
  70436. else {
  70437. result = evaluateCallback(andj);
  70438. }
  70439. }
  70440. else {
  70441. result = andj === "true" ? true : false;
  70442. }
  70443. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  70444. ori = "false";
  70445. break;
  70446. }
  70447. }
  70448. }
  70449. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  70450. result = true;
  70451. break;
  70452. }
  70453. // result equals false (or undefined)
  70454. if (ori !== "true" && ori !== "false") {
  70455. if (ori[0] === "!") {
  70456. result = !evaluateCallback(ori.substring(1));
  70457. }
  70458. else {
  70459. result = evaluateCallback(ori);
  70460. }
  70461. }
  70462. else {
  70463. result = ori === "true" ? true : false;
  70464. }
  70465. }
  70466. }
  70467. // the whole parenthesis scope is replaced by 'true' or 'false'
  70468. return result ? "true" : "false";
  70469. };
  70470. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  70471. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  70472. // remove whitespaces
  70473. r = r.replace(/[\s]/g, function () { return ""; });
  70474. return r.length % 2 ? "!" : "";
  70475. });
  70476. booleanString = booleanString.trim();
  70477. if (booleanString === "!true") {
  70478. booleanString = "false";
  70479. }
  70480. else if (booleanString === "!false") {
  70481. booleanString = "true";
  70482. }
  70483. return booleanString;
  70484. };
  70485. return AndOrNotEvaluator;
  70486. }());
  70487. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  70488. })(BABYLON || (BABYLON = {}));
  70489. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  70490. var BABYLON;
  70491. (function (BABYLON) {
  70492. /**
  70493. * Class used to enable access to IndexedDB
  70494. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  70495. */
  70496. var Database = /** @class */ (function () {
  70497. /**
  70498. * Creates a new Database
  70499. * @param urlToScene defines the url to load the scene
  70500. * @param callbackManifestChecked defines the callback to use when manifest is checked
  70501. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  70502. */
  70503. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  70504. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  70505. var _this = this;
  70506. // Handling various flavors of prefixed version of IndexedDB
  70507. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  70508. this.callbackManifestChecked = callbackManifestChecked;
  70509. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  70510. this.db = null;
  70511. this._enableSceneOffline = false;
  70512. this._enableTexturesOffline = false;
  70513. this.manifestVersionFound = 0;
  70514. this.mustUpdateRessources = false;
  70515. this.hasReachedQuota = false;
  70516. if (!Database.IDBStorageEnabled) {
  70517. this.callbackManifestChecked(true);
  70518. }
  70519. else {
  70520. if (disableManifestCheck) {
  70521. this._enableSceneOffline = true;
  70522. this._enableTexturesOffline = true;
  70523. this.manifestVersionFound = 1;
  70524. BABYLON.Tools.SetImmediate(function () {
  70525. _this.callbackManifestChecked(true);
  70526. });
  70527. }
  70528. else {
  70529. this._checkManifestFile();
  70530. }
  70531. }
  70532. }
  70533. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  70534. /**
  70535. * Gets a boolean indicating if scene must be saved in the database
  70536. */
  70537. get: function () {
  70538. return this._enableSceneOffline;
  70539. },
  70540. enumerable: true,
  70541. configurable: true
  70542. });
  70543. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  70544. /**
  70545. * Gets a boolean indicating if textures must be saved in the database
  70546. */
  70547. get: function () {
  70548. return this._enableTexturesOffline;
  70549. },
  70550. enumerable: true,
  70551. configurable: true
  70552. });
  70553. Database.prototype._checkManifestFile = function () {
  70554. var _this = this;
  70555. var noManifestFile = function () {
  70556. _this._enableSceneOffline = false;
  70557. _this._enableTexturesOffline = false;
  70558. _this.callbackManifestChecked(false);
  70559. };
  70560. var timeStampUsed = false;
  70561. var manifestURL = this.currentSceneUrl + ".manifest";
  70562. var xhr = new XMLHttpRequest();
  70563. if (navigator.onLine) {
  70564. // Adding a timestamp to by-pass browsers' cache
  70565. timeStampUsed = true;
  70566. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  70567. }
  70568. xhr.open("GET", manifestURL, true);
  70569. xhr.addEventListener("load", function () {
  70570. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70571. try {
  70572. var manifestFile = JSON.parse(xhr.response);
  70573. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  70574. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  70575. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  70576. _this.manifestVersionFound = manifestFile.version;
  70577. }
  70578. if (_this.callbackManifestChecked) {
  70579. _this.callbackManifestChecked(true);
  70580. }
  70581. }
  70582. catch (ex) {
  70583. noManifestFile();
  70584. }
  70585. }
  70586. else {
  70587. noManifestFile();
  70588. }
  70589. }, false);
  70590. xhr.addEventListener("error", function (event) {
  70591. if (timeStampUsed) {
  70592. timeStampUsed = false;
  70593. // Let's retry without the timeStamp
  70594. // It could fail when coupled with HTML5 Offline API
  70595. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  70596. xhr.open("GET", retryManifestURL, true);
  70597. xhr.send();
  70598. }
  70599. else {
  70600. noManifestFile();
  70601. }
  70602. }, false);
  70603. try {
  70604. xhr.send();
  70605. }
  70606. catch (ex) {
  70607. BABYLON.Tools.Error("Error on XHR send request.");
  70608. this.callbackManifestChecked(false);
  70609. }
  70610. };
  70611. /**
  70612. * Open the database and make it available
  70613. * @param successCallback defines the callback to call on success
  70614. * @param errorCallback defines the callback to call on error
  70615. */
  70616. Database.prototype.openAsync = function (successCallback, errorCallback) {
  70617. var _this = this;
  70618. var handleError = function () {
  70619. _this.isSupported = false;
  70620. if (errorCallback)
  70621. errorCallback();
  70622. };
  70623. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  70624. // Your browser doesn't support IndexedDB
  70625. this.isSupported = false;
  70626. if (errorCallback)
  70627. errorCallback();
  70628. }
  70629. else {
  70630. // If the DB hasn't been opened or created yet
  70631. if (!this.db) {
  70632. this.hasReachedQuota = false;
  70633. this.isSupported = true;
  70634. var request = this.idbFactory.open("babylonjs", 1);
  70635. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  70636. request.onerror = function (event) {
  70637. handleError();
  70638. };
  70639. // executes when a version change transaction cannot complete due to other active transactions
  70640. request.onblocked = function (event) {
  70641. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  70642. handleError();
  70643. };
  70644. // DB has been opened successfully
  70645. request.onsuccess = function (event) {
  70646. _this.db = request.result;
  70647. successCallback();
  70648. };
  70649. // Initialization of the DB. Creating Scenes & Textures stores
  70650. request.onupgradeneeded = function (event) {
  70651. _this.db = (event.target).result;
  70652. if (_this.db) {
  70653. try {
  70654. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  70655. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  70656. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  70657. }
  70658. catch (ex) {
  70659. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  70660. handleError();
  70661. }
  70662. }
  70663. };
  70664. }
  70665. // DB has already been created and opened
  70666. else {
  70667. if (successCallback)
  70668. successCallback();
  70669. }
  70670. }
  70671. };
  70672. /**
  70673. * Loads an image from the database
  70674. * @param url defines the url to load from
  70675. * @param image defines the target DOM image
  70676. */
  70677. Database.prototype.loadImageFromDB = function (url, image) {
  70678. var _this = this;
  70679. var completeURL = Database._ReturnFullUrlLocation(url);
  70680. var saveAndLoadImage = function () {
  70681. if (!_this.hasReachedQuota && _this.db !== null) {
  70682. // the texture is not yet in the DB, let's try to save it
  70683. _this._saveImageIntoDBAsync(completeURL, image);
  70684. }
  70685. // If the texture is not in the DB and we've reached the DB quota limit
  70686. // let's load it directly from the web
  70687. else {
  70688. image.src = url;
  70689. }
  70690. };
  70691. if (!this.mustUpdateRessources) {
  70692. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  70693. }
  70694. // First time we're download the images or update requested in the manifest file by a version change
  70695. else {
  70696. saveAndLoadImage();
  70697. }
  70698. };
  70699. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  70700. if (this.isSupported && this.db !== null) {
  70701. var texture;
  70702. var transaction = this.db.transaction(["textures"]);
  70703. transaction.onabort = function (event) {
  70704. image.src = url;
  70705. };
  70706. transaction.oncomplete = function (event) {
  70707. var blobTextureURL;
  70708. if (texture) {
  70709. var URL = window.URL || window.webkitURL;
  70710. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  70711. image.onerror = function () {
  70712. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  70713. image.src = url;
  70714. };
  70715. image.src = blobTextureURL;
  70716. }
  70717. else {
  70718. notInDBCallback();
  70719. }
  70720. };
  70721. var getRequest = transaction.objectStore("textures").get(url);
  70722. getRequest.onsuccess = function (event) {
  70723. texture = (event.target).result;
  70724. };
  70725. getRequest.onerror = function (event) {
  70726. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  70727. image.src = url;
  70728. };
  70729. }
  70730. else {
  70731. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70732. image.src = url;
  70733. }
  70734. };
  70735. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  70736. var _this = this;
  70737. if (this.isSupported) {
  70738. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  70739. var generateBlobUrl = function () {
  70740. var blobTextureURL;
  70741. if (blob) {
  70742. var URL = window.URL || window.webkitURL;
  70743. try {
  70744. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  70745. }
  70746. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  70747. catch (ex) {
  70748. blobTextureURL = URL.createObjectURL(blob);
  70749. }
  70750. }
  70751. if (blobTextureURL) {
  70752. image.src = blobTextureURL;
  70753. }
  70754. };
  70755. if (Database.IsUASupportingBlobStorage) { // Create XHR
  70756. var xhr = new XMLHttpRequest(), blob;
  70757. xhr.open("GET", url, true);
  70758. xhr.responseType = "blob";
  70759. xhr.addEventListener("load", function () {
  70760. if (xhr.status === 200 && _this.db) {
  70761. // Blob as response (XHR2)
  70762. blob = xhr.response;
  70763. var transaction = _this.db.transaction(["textures"], "readwrite");
  70764. // the transaction could abort because of a QuotaExceededError error
  70765. transaction.onabort = function (event) {
  70766. try {
  70767. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70768. var srcElement = (event.srcElement || event.target);
  70769. var error = srcElement.error;
  70770. if (error && error.name === "QuotaExceededError") {
  70771. _this.hasReachedQuota = true;
  70772. }
  70773. }
  70774. catch (ex) { }
  70775. generateBlobUrl();
  70776. };
  70777. transaction.oncomplete = function (event) {
  70778. generateBlobUrl();
  70779. };
  70780. var newTexture = { textureUrl: url, data: blob };
  70781. try {
  70782. // Put the blob into the dabase
  70783. var addRequest = transaction.objectStore("textures").put(newTexture);
  70784. addRequest.onsuccess = function (event) {
  70785. };
  70786. addRequest.onerror = function (event) {
  70787. generateBlobUrl();
  70788. };
  70789. }
  70790. catch (ex) {
  70791. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  70792. if (ex.code === 25) {
  70793. Database.IsUASupportingBlobStorage = false;
  70794. }
  70795. image.src = url;
  70796. }
  70797. }
  70798. else {
  70799. image.src = url;
  70800. }
  70801. }, false);
  70802. xhr.addEventListener("error", function (event) {
  70803. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  70804. image.src = url;
  70805. }, false);
  70806. xhr.send();
  70807. }
  70808. else {
  70809. image.src = url;
  70810. }
  70811. }
  70812. else {
  70813. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70814. image.src = url;
  70815. }
  70816. };
  70817. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  70818. var _this = this;
  70819. var updateVersion = function () {
  70820. // the version is not yet in the DB or we need to update it
  70821. _this._saveVersionIntoDBAsync(url, versionLoaded);
  70822. };
  70823. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  70824. };
  70825. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  70826. var _this = this;
  70827. if (this.isSupported && this.db) {
  70828. var version;
  70829. try {
  70830. var transaction = this.db.transaction(["versions"]);
  70831. transaction.oncomplete = function (event) {
  70832. if (version) {
  70833. // If the version in the JSON file is different from the version in DB
  70834. if (_this.manifestVersionFound !== version.data) {
  70835. _this.mustUpdateRessources = true;
  70836. updateInDBCallback();
  70837. }
  70838. else {
  70839. callback(version.data);
  70840. }
  70841. }
  70842. // version was not found in DB
  70843. else {
  70844. _this.mustUpdateRessources = true;
  70845. updateInDBCallback();
  70846. }
  70847. };
  70848. transaction.onabort = function (event) {
  70849. callback(-1);
  70850. };
  70851. var getRequest = transaction.objectStore("versions").get(url);
  70852. getRequest.onsuccess = function (event) {
  70853. version = (event.target).result;
  70854. };
  70855. getRequest.onerror = function (event) {
  70856. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  70857. callback(-1);
  70858. };
  70859. }
  70860. catch (ex) {
  70861. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  70862. callback(-1);
  70863. }
  70864. }
  70865. else {
  70866. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70867. callback(-1);
  70868. }
  70869. };
  70870. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  70871. var _this = this;
  70872. if (this.isSupported && !this.hasReachedQuota && this.db) {
  70873. try {
  70874. // Open a transaction to the database
  70875. var transaction = this.db.transaction(["versions"], "readwrite");
  70876. // the transaction could abort because of a QuotaExceededError error
  70877. transaction.onabort = function (event) {
  70878. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70879. var error = event.srcElement['error'];
  70880. if (error && error.name === "QuotaExceededError") {
  70881. _this.hasReachedQuota = true;
  70882. }
  70883. }
  70884. catch (ex) { }
  70885. callback(-1);
  70886. };
  70887. transaction.oncomplete = function (event) {
  70888. callback(_this.manifestVersionFound);
  70889. };
  70890. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  70891. // Put the scene into the database
  70892. var addRequest = transaction.objectStore("versions").put(newVersion);
  70893. addRequest.onsuccess = function (event) {
  70894. };
  70895. addRequest.onerror = function (event) {
  70896. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  70897. };
  70898. }
  70899. catch (ex) {
  70900. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  70901. callback(-1);
  70902. }
  70903. }
  70904. else {
  70905. callback(-1);
  70906. }
  70907. };
  70908. /**
  70909. * Loads a file from database
  70910. * @param url defines the URL to load from
  70911. * @param sceneLoaded defines a callback to call on success
  70912. * @param progressCallBack defines a callback to call when progress changed
  70913. * @param errorCallback defines a callback to call on error
  70914. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  70915. */
  70916. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  70917. var _this = this;
  70918. var completeUrl = Database._ReturnFullUrlLocation(url);
  70919. var saveAndLoadFile = function () {
  70920. // the scene is not yet in the DB, let's try to save it
  70921. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  70922. };
  70923. this._checkVersionFromDB(completeUrl, function (version) {
  70924. if (version !== -1) {
  70925. if (!_this.mustUpdateRessources) {
  70926. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  70927. }
  70928. else {
  70929. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  70930. }
  70931. }
  70932. else {
  70933. if (errorCallback) {
  70934. errorCallback();
  70935. }
  70936. }
  70937. });
  70938. };
  70939. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  70940. if (this.isSupported && this.db) {
  70941. var targetStore;
  70942. if (url.indexOf(".babylon") !== -1) {
  70943. targetStore = "scenes";
  70944. }
  70945. else {
  70946. targetStore = "textures";
  70947. }
  70948. var file;
  70949. var transaction = this.db.transaction([targetStore]);
  70950. transaction.oncomplete = function (event) {
  70951. if (file) {
  70952. callback(file.data);
  70953. }
  70954. // file was not found in DB
  70955. else {
  70956. notInDBCallback();
  70957. }
  70958. };
  70959. transaction.onabort = function (event) {
  70960. notInDBCallback();
  70961. };
  70962. var getRequest = transaction.objectStore(targetStore).get(url);
  70963. getRequest.onsuccess = function (event) {
  70964. file = (event.target).result;
  70965. };
  70966. getRequest.onerror = function (event) {
  70967. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  70968. notInDBCallback();
  70969. };
  70970. }
  70971. else {
  70972. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70973. callback();
  70974. }
  70975. };
  70976. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  70977. var _this = this;
  70978. if (this.isSupported) {
  70979. var targetStore;
  70980. if (url.indexOf(".babylon") !== -1) {
  70981. targetStore = "scenes";
  70982. }
  70983. else {
  70984. targetStore = "textures";
  70985. }
  70986. // Create XHR
  70987. var xhr = new XMLHttpRequest();
  70988. var fileData;
  70989. xhr.open("GET", url, true);
  70990. if (useArrayBuffer) {
  70991. xhr.responseType = "arraybuffer";
  70992. }
  70993. if (progressCallback) {
  70994. xhr.onprogress = progressCallback;
  70995. }
  70996. xhr.addEventListener("load", function () {
  70997. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  70998. // Blob as response (XHR2)
  70999. //fileData = xhr.responseText;
  71000. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  71001. if (!_this.hasReachedQuota && _this.db) {
  71002. // Open a transaction to the database
  71003. var transaction = _this.db.transaction([targetStore], "readwrite");
  71004. // the transaction could abort because of a QuotaExceededError error
  71005. transaction.onabort = function (event) {
  71006. try {
  71007. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71008. var error = event.srcElement['error'];
  71009. if (error && error.name === "QuotaExceededError") {
  71010. _this.hasReachedQuota = true;
  71011. }
  71012. }
  71013. catch (ex) { }
  71014. callback(fileData);
  71015. };
  71016. transaction.oncomplete = function (event) {
  71017. callback(fileData);
  71018. };
  71019. var newFile;
  71020. if (targetStore === "scenes") {
  71021. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  71022. }
  71023. else {
  71024. newFile = { textureUrl: url, data: fileData };
  71025. }
  71026. try {
  71027. // Put the scene into the database
  71028. var addRequest = transaction.objectStore(targetStore).put(newFile);
  71029. addRequest.onsuccess = function (event) {
  71030. };
  71031. addRequest.onerror = function (event) {
  71032. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  71033. };
  71034. }
  71035. catch (ex) {
  71036. callback(fileData);
  71037. }
  71038. }
  71039. else {
  71040. callback(fileData);
  71041. }
  71042. }
  71043. else {
  71044. if (xhr.status >= 400 && errorCallback) {
  71045. errorCallback(xhr);
  71046. }
  71047. else {
  71048. callback();
  71049. }
  71050. }
  71051. }, false);
  71052. xhr.addEventListener("error", function (event) {
  71053. BABYLON.Tools.Error("error on XHR request.");
  71054. callback();
  71055. }, false);
  71056. xhr.send();
  71057. }
  71058. else {
  71059. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71060. callback();
  71061. }
  71062. };
  71063. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  71064. Database.IsUASupportingBlobStorage = true;
  71065. /** Gets a boolean indicating if Database storate is enabled */
  71066. Database.IDBStorageEnabled = true;
  71067. Database._ParseURL = function (url) {
  71068. var a = document.createElement('a');
  71069. a.href = url;
  71070. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  71071. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  71072. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  71073. return absLocation;
  71074. };
  71075. Database._ReturnFullUrlLocation = function (url) {
  71076. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  71077. return (Database._ParseURL(window.location.href) + url);
  71078. }
  71079. else {
  71080. return url;
  71081. }
  71082. };
  71083. return Database;
  71084. }());
  71085. BABYLON.Database = Database;
  71086. })(BABYLON || (BABYLON = {}));
  71087. //# sourceMappingURL=babylon.database.js.map
  71088. var BABYLON;
  71089. (function (BABYLON) {
  71090. var FresnelParameters = /** @class */ (function () {
  71091. function FresnelParameters() {
  71092. this._isEnabled = true;
  71093. this.leftColor = BABYLON.Color3.White();
  71094. this.rightColor = BABYLON.Color3.Black();
  71095. this.bias = 0;
  71096. this.power = 1;
  71097. }
  71098. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  71099. get: function () {
  71100. return this._isEnabled;
  71101. },
  71102. set: function (value) {
  71103. if (this._isEnabled === value) {
  71104. return;
  71105. }
  71106. this._isEnabled = value;
  71107. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  71108. },
  71109. enumerable: true,
  71110. configurable: true
  71111. });
  71112. FresnelParameters.prototype.clone = function () {
  71113. var newFresnelParameters = new FresnelParameters();
  71114. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  71115. return newFresnelParameters;
  71116. };
  71117. FresnelParameters.prototype.serialize = function () {
  71118. var serializationObject = {};
  71119. serializationObject.isEnabled = this.isEnabled;
  71120. serializationObject.leftColor = this.leftColor.asArray();
  71121. serializationObject.rightColor = this.rightColor.asArray();
  71122. serializationObject.bias = this.bias;
  71123. serializationObject.power = this.power;
  71124. return serializationObject;
  71125. };
  71126. FresnelParameters.Parse = function (parsedFresnelParameters) {
  71127. var fresnelParameters = new FresnelParameters();
  71128. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  71129. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  71130. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  71131. fresnelParameters.bias = parsedFresnelParameters.bias;
  71132. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  71133. return fresnelParameters;
  71134. };
  71135. return FresnelParameters;
  71136. }());
  71137. BABYLON.FresnelParameters = FresnelParameters;
  71138. })(BABYLON || (BABYLON = {}));
  71139. //# sourceMappingURL=babylon.fresnelParameters.js.map
  71140. var BABYLON;
  71141. (function (BABYLON) {
  71142. var MultiMaterial = /** @class */ (function (_super) {
  71143. __extends(MultiMaterial, _super);
  71144. function MultiMaterial(name, scene) {
  71145. var _this = _super.call(this, name, scene, true) || this;
  71146. scene.multiMaterials.push(_this);
  71147. _this.subMaterials = new Array();
  71148. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  71149. return _this;
  71150. }
  71151. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  71152. get: function () {
  71153. return this._subMaterials;
  71154. },
  71155. set: function (value) {
  71156. this._subMaterials = value;
  71157. this._hookArray(value);
  71158. },
  71159. enumerable: true,
  71160. configurable: true
  71161. });
  71162. MultiMaterial.prototype._hookArray = function (array) {
  71163. var _this = this;
  71164. var oldPush = array.push;
  71165. array.push = function () {
  71166. var items = [];
  71167. for (var _i = 0; _i < arguments.length; _i++) {
  71168. items[_i] = arguments[_i];
  71169. }
  71170. var result = oldPush.apply(array, items);
  71171. _this._markAllSubMeshesAsTexturesDirty();
  71172. return result;
  71173. };
  71174. var oldSplice = array.splice;
  71175. array.splice = function (index, deleteCount) {
  71176. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71177. _this._markAllSubMeshesAsTexturesDirty();
  71178. return deleted;
  71179. };
  71180. };
  71181. // Properties
  71182. MultiMaterial.prototype.getSubMaterial = function (index) {
  71183. if (index < 0 || index >= this.subMaterials.length) {
  71184. return this.getScene().defaultMaterial;
  71185. }
  71186. return this.subMaterials[index];
  71187. };
  71188. MultiMaterial.prototype.getActiveTextures = function () {
  71189. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  71190. if (subMaterial) {
  71191. return subMaterial.getActiveTextures();
  71192. }
  71193. else {
  71194. return [];
  71195. }
  71196. }));
  71197. var _a;
  71198. };
  71199. // Methods
  71200. MultiMaterial.prototype.getClassName = function () {
  71201. return "MultiMaterial";
  71202. };
  71203. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  71204. for (var index = 0; index < this.subMaterials.length; index++) {
  71205. var subMaterial = this.subMaterials[index];
  71206. if (subMaterial) {
  71207. if (subMaterial.storeEffectOnSubMeshes) {
  71208. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  71209. return false;
  71210. }
  71211. continue;
  71212. }
  71213. if (!subMaterial.isReady(mesh)) {
  71214. return false;
  71215. }
  71216. }
  71217. }
  71218. return true;
  71219. };
  71220. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  71221. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  71222. for (var index = 0; index < this.subMaterials.length; index++) {
  71223. var subMaterial = null;
  71224. var current = this.subMaterials[index];
  71225. if (cloneChildren && current) {
  71226. subMaterial = current.clone(name + "-" + current.name);
  71227. }
  71228. else {
  71229. subMaterial = this.subMaterials[index];
  71230. }
  71231. newMultiMaterial.subMaterials.push(subMaterial);
  71232. }
  71233. return newMultiMaterial;
  71234. };
  71235. MultiMaterial.prototype.serialize = function () {
  71236. var serializationObject = {};
  71237. serializationObject.name = this.name;
  71238. serializationObject.id = this.id;
  71239. if (BABYLON.Tags) {
  71240. serializationObject.tags = BABYLON.Tags.GetTags(this);
  71241. }
  71242. serializationObject.materials = [];
  71243. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  71244. var subMat = this.subMaterials[matIndex];
  71245. if (subMat) {
  71246. serializationObject.materials.push(subMat.id);
  71247. }
  71248. else {
  71249. serializationObject.materials.push(null);
  71250. }
  71251. }
  71252. return serializationObject;
  71253. };
  71254. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  71255. var scene = this.getScene();
  71256. if (!scene) {
  71257. return;
  71258. }
  71259. var index = scene.multiMaterials.indexOf(this);
  71260. if (index >= 0) {
  71261. scene.multiMaterials.splice(index, 1);
  71262. }
  71263. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  71264. };
  71265. return MultiMaterial;
  71266. }(BABYLON.Material));
  71267. BABYLON.MultiMaterial = MultiMaterial;
  71268. })(BABYLON || (BABYLON = {}));
  71269. //# sourceMappingURL=babylon.multiMaterial.js.map
  71270. var BABYLON;
  71271. (function (BABYLON) {
  71272. var FreeCameraTouchInput = /** @class */ (function () {
  71273. function FreeCameraTouchInput() {
  71274. this._offsetX = null;
  71275. this._offsetY = null;
  71276. this._pointerPressed = new Array();
  71277. this.touchAngularSensibility = 200000.0;
  71278. this.touchMoveSensibility = 250.0;
  71279. }
  71280. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  71281. var _this = this;
  71282. var previousPosition = null;
  71283. if (this._pointerInput === undefined) {
  71284. this._onLostFocus = function (evt) {
  71285. _this._offsetX = null;
  71286. _this._offsetY = null;
  71287. };
  71288. this._pointerInput = function (p, s) {
  71289. var evt = p.event;
  71290. if (evt.pointerType === "mouse") {
  71291. return;
  71292. }
  71293. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71294. if (!noPreventDefault) {
  71295. evt.preventDefault();
  71296. }
  71297. _this._pointerPressed.push(evt.pointerId);
  71298. if (_this._pointerPressed.length !== 1) {
  71299. return;
  71300. }
  71301. previousPosition = {
  71302. x: evt.clientX,
  71303. y: evt.clientY
  71304. };
  71305. }
  71306. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  71307. if (!noPreventDefault) {
  71308. evt.preventDefault();
  71309. }
  71310. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71311. if (index === -1) {
  71312. return;
  71313. }
  71314. _this._pointerPressed.splice(index, 1);
  71315. if (index != 0) {
  71316. return;
  71317. }
  71318. previousPosition = null;
  71319. _this._offsetX = null;
  71320. _this._offsetY = null;
  71321. }
  71322. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  71323. if (!noPreventDefault) {
  71324. evt.preventDefault();
  71325. }
  71326. if (!previousPosition) {
  71327. return;
  71328. }
  71329. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71330. if (index != 0) {
  71331. return;
  71332. }
  71333. _this._offsetX = evt.clientX - previousPosition.x;
  71334. _this._offsetY = -(evt.clientY - previousPosition.y);
  71335. }
  71336. };
  71337. }
  71338. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  71339. if (this._onLostFocus) {
  71340. element.addEventListener("blur", this._onLostFocus);
  71341. }
  71342. };
  71343. FreeCameraTouchInput.prototype.detachControl = function (element) {
  71344. if (this._pointerInput && element) {
  71345. if (this._observer) {
  71346. this.camera.getScene().onPointerObservable.remove(this._observer);
  71347. this._observer = null;
  71348. }
  71349. if (this._onLostFocus) {
  71350. element.removeEventListener("blur", this._onLostFocus);
  71351. this._onLostFocus = null;
  71352. }
  71353. this._pointerPressed = [];
  71354. this._offsetX = null;
  71355. this._offsetY = null;
  71356. }
  71357. };
  71358. FreeCameraTouchInput.prototype.checkInputs = function () {
  71359. if (this._offsetX && this._offsetY) {
  71360. var camera = this.camera;
  71361. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  71362. if (this._pointerPressed.length > 1) {
  71363. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  71364. }
  71365. else {
  71366. var speed = camera._computeLocalCameraSpeed();
  71367. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  71368. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  71369. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  71370. }
  71371. }
  71372. };
  71373. FreeCameraTouchInput.prototype.getClassName = function () {
  71374. return "FreeCameraTouchInput";
  71375. };
  71376. FreeCameraTouchInput.prototype.getSimpleName = function () {
  71377. return "touch";
  71378. };
  71379. __decorate([
  71380. BABYLON.serialize()
  71381. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  71382. __decorate([
  71383. BABYLON.serialize()
  71384. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  71385. return FreeCameraTouchInput;
  71386. }());
  71387. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  71388. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  71389. })(BABYLON || (BABYLON = {}));
  71390. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  71391. var BABYLON;
  71392. (function (BABYLON) {
  71393. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  71394. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  71395. });
  71396. // We're mainly based on the logic defined into the FreeCamera code
  71397. var TouchCamera = /** @class */ (function (_super) {
  71398. __extends(TouchCamera, _super);
  71399. //-- end properties for backward compatibility for inputs
  71400. function TouchCamera(name, position, scene) {
  71401. var _this = _super.call(this, name, position, scene) || this;
  71402. _this.inputs.addTouch();
  71403. _this._setupInputs();
  71404. return _this;
  71405. }
  71406. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  71407. //-- Begin properties for backward compatibility for inputs
  71408. get: function () {
  71409. var touch = this.inputs.attached["touch"];
  71410. if (touch)
  71411. return touch.touchAngularSensibility;
  71412. return 0;
  71413. },
  71414. set: function (value) {
  71415. var touch = this.inputs.attached["touch"];
  71416. if (touch)
  71417. touch.touchAngularSensibility = value;
  71418. },
  71419. enumerable: true,
  71420. configurable: true
  71421. });
  71422. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  71423. get: function () {
  71424. var touch = this.inputs.attached["touch"];
  71425. if (touch)
  71426. return touch.touchMoveSensibility;
  71427. return 0;
  71428. },
  71429. set: function (value) {
  71430. var touch = this.inputs.attached["touch"];
  71431. if (touch)
  71432. touch.touchMoveSensibility = value;
  71433. },
  71434. enumerable: true,
  71435. configurable: true
  71436. });
  71437. TouchCamera.prototype.getClassName = function () {
  71438. return "TouchCamera";
  71439. };
  71440. TouchCamera.prototype._setupInputs = function () {
  71441. var mouse = this.inputs.attached["mouse"];
  71442. if (mouse) {
  71443. mouse.touchEnabled = false;
  71444. }
  71445. };
  71446. return TouchCamera;
  71447. }(BABYLON.FreeCamera));
  71448. BABYLON.TouchCamera = TouchCamera;
  71449. })(BABYLON || (BABYLON = {}));
  71450. //# sourceMappingURL=babylon.touchCamera.js.map
  71451. var BABYLON;
  71452. (function (BABYLON) {
  71453. var ProceduralTexture = /** @class */ (function (_super) {
  71454. __extends(ProceduralTexture, _super);
  71455. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  71456. if (fallbackTexture === void 0) { fallbackTexture = null; }
  71457. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71458. if (isCube === void 0) { isCube = false; }
  71459. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71460. _this.isCube = isCube;
  71461. _this.isEnabled = true;
  71462. _this._currentRefreshId = -1;
  71463. _this._refreshRate = 1;
  71464. _this._vertexBuffers = {};
  71465. _this._uniforms = new Array();
  71466. _this._samplers = new Array();
  71467. _this._textures = {};
  71468. _this._floats = {};
  71469. _this._ints = {};
  71470. _this._floatsArrays = {};
  71471. _this._colors3 = {};
  71472. _this._colors4 = {};
  71473. _this._vectors2 = {};
  71474. _this._vectors3 = {};
  71475. _this._matrices = {};
  71476. _this._fallbackTextureUsed = false;
  71477. scene = _this.getScene();
  71478. scene.proceduralTextures.push(_this);
  71479. _this._engine = scene.getEngine();
  71480. _this.name = name;
  71481. _this.isRenderTarget = true;
  71482. _this._size = size;
  71483. _this._generateMipMaps = generateMipMaps;
  71484. _this.setFragment(fragment);
  71485. _this._fallbackTexture = fallbackTexture;
  71486. if (isCube) {
  71487. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  71488. _this.setFloat("face", 0);
  71489. }
  71490. else {
  71491. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  71492. }
  71493. // VBO
  71494. var vertices = [];
  71495. vertices.push(1, 1);
  71496. vertices.push(-1, 1);
  71497. vertices.push(-1, -1);
  71498. vertices.push(1, -1);
  71499. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71500. _this._createIndexBuffer();
  71501. return _this;
  71502. }
  71503. ProceduralTexture.prototype._createIndexBuffer = function () {
  71504. var engine = this._engine;
  71505. // Indices
  71506. var indices = [];
  71507. indices.push(0);
  71508. indices.push(1);
  71509. indices.push(2);
  71510. indices.push(0);
  71511. indices.push(2);
  71512. indices.push(3);
  71513. this._indexBuffer = engine.createIndexBuffer(indices);
  71514. };
  71515. ProceduralTexture.prototype._rebuild = function () {
  71516. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71517. if (vb) {
  71518. vb._rebuild();
  71519. }
  71520. this._createIndexBuffer();
  71521. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  71522. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  71523. }
  71524. };
  71525. ProceduralTexture.prototype.reset = function () {
  71526. if (this._effect === undefined) {
  71527. return;
  71528. }
  71529. var engine = this._engine;
  71530. engine._releaseEffect(this._effect);
  71531. };
  71532. ProceduralTexture.prototype.isReady = function () {
  71533. var _this = this;
  71534. var engine = this._engine;
  71535. var shaders;
  71536. if (!this._fragment) {
  71537. return false;
  71538. }
  71539. if (this._fallbackTextureUsed) {
  71540. return true;
  71541. }
  71542. if (this._fragment.fragmentElement !== undefined) {
  71543. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  71544. }
  71545. else {
  71546. shaders = { vertex: "procedural", fragment: this._fragment };
  71547. }
  71548. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  71549. _this.releaseInternalTexture();
  71550. if (_this._fallbackTexture) {
  71551. _this._texture = _this._fallbackTexture._texture;
  71552. if (_this._texture) {
  71553. _this._texture.incrementReferences();
  71554. }
  71555. }
  71556. _this._fallbackTextureUsed = true;
  71557. });
  71558. return this._effect.isReady();
  71559. };
  71560. ProceduralTexture.prototype.resetRefreshCounter = function () {
  71561. this._currentRefreshId = -1;
  71562. };
  71563. ProceduralTexture.prototype.setFragment = function (fragment) {
  71564. this._fragment = fragment;
  71565. };
  71566. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  71567. get: function () {
  71568. return this._refreshRate;
  71569. },
  71570. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71571. set: function (value) {
  71572. this._refreshRate = value;
  71573. this.resetRefreshCounter();
  71574. },
  71575. enumerable: true,
  71576. configurable: true
  71577. });
  71578. ProceduralTexture.prototype._shouldRender = function () {
  71579. if (!this.isEnabled || !this.isReady() || !this._texture) {
  71580. return false;
  71581. }
  71582. if (this._fallbackTextureUsed) {
  71583. return false;
  71584. }
  71585. if (this._currentRefreshId === -1) { // At least render once
  71586. this._currentRefreshId = 1;
  71587. return true;
  71588. }
  71589. if (this.refreshRate === this._currentRefreshId) {
  71590. this._currentRefreshId = 1;
  71591. return true;
  71592. }
  71593. this._currentRefreshId++;
  71594. return false;
  71595. };
  71596. ProceduralTexture.prototype.getRenderSize = function () {
  71597. return this._size;
  71598. };
  71599. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  71600. if (this._fallbackTextureUsed) {
  71601. return;
  71602. }
  71603. this.releaseInternalTexture();
  71604. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  71605. // Update properties
  71606. this._size = size;
  71607. this._generateMipMaps = generateMipMaps;
  71608. };
  71609. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  71610. if (this._uniforms.indexOf(uniformName) === -1) {
  71611. this._uniforms.push(uniformName);
  71612. }
  71613. };
  71614. ProceduralTexture.prototype.setTexture = function (name, texture) {
  71615. if (this._samplers.indexOf(name) === -1) {
  71616. this._samplers.push(name);
  71617. }
  71618. this._textures[name] = texture;
  71619. return this;
  71620. };
  71621. ProceduralTexture.prototype.setFloat = function (name, value) {
  71622. this._checkUniform(name);
  71623. this._floats[name] = value;
  71624. return this;
  71625. };
  71626. /**
  71627. * Set the value of an uniform to an integer value
  71628. * @param name defines the name of the uniform
  71629. * @param value defines the value to set
  71630. * @returns the current procedural texture
  71631. */
  71632. ProceduralTexture.prototype.setInt = function (name, value) {
  71633. this._checkUniform(name);
  71634. this._ints[name] = value;
  71635. return this;
  71636. };
  71637. ProceduralTexture.prototype.setFloats = function (name, value) {
  71638. this._checkUniform(name);
  71639. this._floatsArrays[name] = value;
  71640. return this;
  71641. };
  71642. ProceduralTexture.prototype.setColor3 = function (name, value) {
  71643. this._checkUniform(name);
  71644. this._colors3[name] = value;
  71645. return this;
  71646. };
  71647. ProceduralTexture.prototype.setColor4 = function (name, value) {
  71648. this._checkUniform(name);
  71649. this._colors4[name] = value;
  71650. return this;
  71651. };
  71652. ProceduralTexture.prototype.setVector2 = function (name, value) {
  71653. this._checkUniform(name);
  71654. this._vectors2[name] = value;
  71655. return this;
  71656. };
  71657. ProceduralTexture.prototype.setVector3 = function (name, value) {
  71658. this._checkUniform(name);
  71659. this._vectors3[name] = value;
  71660. return this;
  71661. };
  71662. ProceduralTexture.prototype.setMatrix = function (name, value) {
  71663. this._checkUniform(name);
  71664. this._matrices[name] = value;
  71665. return this;
  71666. };
  71667. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71668. var scene = this.getScene();
  71669. if (!scene) {
  71670. return;
  71671. }
  71672. var engine = this._engine;
  71673. // Render
  71674. engine.enableEffect(this._effect);
  71675. engine.setState(false);
  71676. // Texture
  71677. for (var name in this._textures) {
  71678. this._effect.setTexture(name, this._textures[name]);
  71679. }
  71680. // Float
  71681. for (name in this._ints) {
  71682. this._effect.setInt(name, this._ints[name]);
  71683. }
  71684. // Float
  71685. for (name in this._floats) {
  71686. this._effect.setFloat(name, this._floats[name]);
  71687. }
  71688. // Floats
  71689. for (name in this._floatsArrays) {
  71690. this._effect.setArray(name, this._floatsArrays[name]);
  71691. }
  71692. // Color3
  71693. for (name in this._colors3) {
  71694. this._effect.setColor3(name, this._colors3[name]);
  71695. }
  71696. // Color4
  71697. for (name in this._colors4) {
  71698. var color = this._colors4[name];
  71699. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  71700. }
  71701. // Vector2
  71702. for (name in this._vectors2) {
  71703. this._effect.setVector2(name, this._vectors2[name]);
  71704. }
  71705. // Vector3
  71706. for (name in this._vectors3) {
  71707. this._effect.setVector3(name, this._vectors3[name]);
  71708. }
  71709. // Matrix
  71710. for (name in this._matrices) {
  71711. this._effect.setMatrix(name, this._matrices[name]);
  71712. }
  71713. if (!this._texture) {
  71714. return;
  71715. }
  71716. if (this.isCube) {
  71717. for (var face = 0; face < 6; face++) {
  71718. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  71719. // VBOs
  71720. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71721. this._effect.setFloat("face", face);
  71722. // Clear
  71723. engine.clear(scene.clearColor, true, true, true);
  71724. // Draw order
  71725. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71726. // Mipmaps
  71727. if (face === 5) {
  71728. engine.generateMipMapsForCubemap(this._texture);
  71729. }
  71730. }
  71731. }
  71732. else {
  71733. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  71734. // VBOs
  71735. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71736. // Clear
  71737. engine.clear(scene.clearColor, true, true, true);
  71738. // Draw order
  71739. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71740. }
  71741. // Unbind
  71742. engine.unBindFramebuffer(this._texture, this.isCube);
  71743. if (this.onGenerated) {
  71744. this.onGenerated();
  71745. }
  71746. };
  71747. ProceduralTexture.prototype.clone = function () {
  71748. var textureSize = this.getSize();
  71749. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  71750. // Base texture
  71751. newTexture.hasAlpha = this.hasAlpha;
  71752. newTexture.level = this.level;
  71753. // RenderTarget Texture
  71754. newTexture.coordinatesMode = this.coordinatesMode;
  71755. return newTexture;
  71756. };
  71757. ProceduralTexture.prototype.dispose = function () {
  71758. var scene = this.getScene();
  71759. if (!scene) {
  71760. return;
  71761. }
  71762. var index = scene.proceduralTextures.indexOf(this);
  71763. if (index >= 0) {
  71764. scene.proceduralTextures.splice(index, 1);
  71765. }
  71766. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71767. if (vertexBuffer) {
  71768. vertexBuffer.dispose();
  71769. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71770. }
  71771. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  71772. this._indexBuffer = null;
  71773. }
  71774. _super.prototype.dispose.call(this);
  71775. };
  71776. __decorate([
  71777. BABYLON.serialize()
  71778. ], ProceduralTexture.prototype, "_size", void 0);
  71779. __decorate([
  71780. BABYLON.serialize()
  71781. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  71782. __decorate([
  71783. BABYLON.serialize()
  71784. ], ProceduralTexture.prototype, "isEnabled", void 0);
  71785. __decorate([
  71786. BABYLON.serialize()
  71787. ], ProceduralTexture.prototype, "refreshRate", null);
  71788. return ProceduralTexture;
  71789. }(BABYLON.Texture));
  71790. BABYLON.ProceduralTexture = ProceduralTexture;
  71791. })(BABYLON || (BABYLON = {}));
  71792. //# sourceMappingURL=babylon.proceduralTexture.js.map
  71793. var BABYLON;
  71794. (function (BABYLON) {
  71795. var CustomProceduralTexture = /** @class */ (function (_super) {
  71796. __extends(CustomProceduralTexture, _super);
  71797. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  71798. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  71799. _this._animate = true;
  71800. _this._time = 0;
  71801. _this._texturePath = texturePath;
  71802. //Try to load json
  71803. _this.loadJson(texturePath);
  71804. _this.refreshRate = 1;
  71805. return _this;
  71806. }
  71807. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  71808. var _this = this;
  71809. var noConfigFile = function () {
  71810. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  71811. try {
  71812. _this.setFragment(_this._texturePath);
  71813. }
  71814. catch (ex) {
  71815. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  71816. }
  71817. };
  71818. var configFileUrl = jsonUrl + "/config.json";
  71819. var xhr = new XMLHttpRequest();
  71820. xhr.open("GET", configFileUrl, true);
  71821. xhr.addEventListener("load", function () {
  71822. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  71823. try {
  71824. _this._config = JSON.parse(xhr.response);
  71825. _this.updateShaderUniforms();
  71826. _this.updateTextures();
  71827. _this.setFragment(_this._texturePath + "/custom");
  71828. _this._animate = _this._config.animate;
  71829. _this.refreshRate = _this._config.refreshrate;
  71830. }
  71831. catch (ex) {
  71832. noConfigFile();
  71833. }
  71834. }
  71835. else {
  71836. noConfigFile();
  71837. }
  71838. }, false);
  71839. xhr.addEventListener("error", function () {
  71840. noConfigFile();
  71841. }, false);
  71842. try {
  71843. xhr.send();
  71844. }
  71845. catch (ex) {
  71846. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  71847. }
  71848. };
  71849. CustomProceduralTexture.prototype.isReady = function () {
  71850. if (!_super.prototype.isReady.call(this)) {
  71851. return false;
  71852. }
  71853. for (var name in this._textures) {
  71854. var texture = this._textures[name];
  71855. if (!texture.isReady()) {
  71856. return false;
  71857. }
  71858. }
  71859. return true;
  71860. };
  71861. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71862. var scene = this.getScene();
  71863. if (this._animate && scene) {
  71864. this._time += scene.getAnimationRatio() * 0.03;
  71865. this.updateShaderUniforms();
  71866. }
  71867. _super.prototype.render.call(this, useCameraPostProcess);
  71868. };
  71869. CustomProceduralTexture.prototype.updateTextures = function () {
  71870. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  71871. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  71872. }
  71873. };
  71874. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  71875. if (this._config) {
  71876. for (var j = 0; j < this._config.uniforms.length; j++) {
  71877. var uniform = this._config.uniforms[j];
  71878. switch (uniform.type) {
  71879. case "float":
  71880. this.setFloat(uniform.name, uniform.value);
  71881. break;
  71882. case "color3":
  71883. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  71884. break;
  71885. case "color4":
  71886. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  71887. break;
  71888. case "vector2":
  71889. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  71890. break;
  71891. case "vector3":
  71892. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  71893. break;
  71894. }
  71895. }
  71896. }
  71897. this.setFloat("time", this._time);
  71898. };
  71899. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  71900. get: function () {
  71901. return this._animate;
  71902. },
  71903. set: function (value) {
  71904. this._animate = value;
  71905. },
  71906. enumerable: true,
  71907. configurable: true
  71908. });
  71909. return CustomProceduralTexture;
  71910. }(BABYLON.ProceduralTexture));
  71911. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  71912. })(BABYLON || (BABYLON = {}));
  71913. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  71914. var BABYLON;
  71915. (function (BABYLON) {
  71916. var FreeCameraGamepadInput = /** @class */ (function () {
  71917. function FreeCameraGamepadInput() {
  71918. this.gamepadAngularSensibility = 200;
  71919. this.gamepadMoveSensibility = 40;
  71920. // private members
  71921. this._cameraTransform = BABYLON.Matrix.Identity();
  71922. this._deltaTransform = BABYLON.Vector3.Zero();
  71923. this._vector3 = BABYLON.Vector3.Zero();
  71924. this._vector2 = BABYLON.Vector2.Zero();
  71925. }
  71926. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71927. var _this = this;
  71928. var manager = this.camera.getScene().gamepadManager;
  71929. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71930. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71931. // prioritize XBOX gamepads.
  71932. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71933. _this.gamepad = gamepad;
  71934. }
  71935. }
  71936. });
  71937. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71938. if (_this.gamepad === gamepad) {
  71939. _this.gamepad = null;
  71940. }
  71941. });
  71942. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71943. };
  71944. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  71945. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71946. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71947. this.gamepad = null;
  71948. };
  71949. FreeCameraGamepadInput.prototype.checkInputs = function () {
  71950. if (this.gamepad && this.gamepad.leftStick) {
  71951. var camera = this.camera;
  71952. var LSValues = this.gamepad.leftStick;
  71953. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  71954. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71955. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  71956. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  71957. var RSValues = this.gamepad.rightStick;
  71958. if (RSValues) {
  71959. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  71960. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  71961. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  71962. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  71963. }
  71964. else {
  71965. RSValues = { x: 0, y: 0 };
  71966. }
  71967. if (!camera.rotationQuaternion) {
  71968. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  71969. }
  71970. else {
  71971. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  71972. }
  71973. var speed = camera._computeLocalCameraSpeed() * 50.0;
  71974. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  71975. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  71976. camera.cameraDirection.addInPlace(this._deltaTransform);
  71977. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  71978. camera.cameraRotation.addInPlace(this._vector2);
  71979. }
  71980. };
  71981. FreeCameraGamepadInput.prototype.getClassName = function () {
  71982. return "FreeCameraGamepadInput";
  71983. };
  71984. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  71985. return "gamepad";
  71986. };
  71987. __decorate([
  71988. BABYLON.serialize()
  71989. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  71990. __decorate([
  71991. BABYLON.serialize()
  71992. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71993. return FreeCameraGamepadInput;
  71994. }());
  71995. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  71996. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  71997. })(BABYLON || (BABYLON = {}));
  71998. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  71999. var BABYLON;
  72000. (function (BABYLON) {
  72001. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  72002. function ArcRotateCameraGamepadInput() {
  72003. this.gamepadRotationSensibility = 80;
  72004. this.gamepadMoveSensibility = 40;
  72005. }
  72006. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  72007. var _this = this;
  72008. var manager = this.camera.getScene().gamepadManager;
  72009. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72010. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72011. // prioritize XBOX gamepads.
  72012. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  72013. _this.gamepad = gamepad;
  72014. }
  72015. }
  72016. });
  72017. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72018. if (_this.gamepad === gamepad) {
  72019. _this.gamepad = null;
  72020. }
  72021. });
  72022. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  72023. };
  72024. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  72025. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72026. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72027. this.gamepad = null;
  72028. };
  72029. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  72030. if (this.gamepad) {
  72031. var camera = this.camera;
  72032. var RSValues = this.gamepad.rightStick;
  72033. if (RSValues) {
  72034. if (RSValues.x != 0) {
  72035. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  72036. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  72037. camera.inertialAlphaOffset += normalizedRX;
  72038. }
  72039. }
  72040. if (RSValues.y != 0) {
  72041. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  72042. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  72043. camera.inertialBetaOffset += normalizedRY;
  72044. }
  72045. }
  72046. }
  72047. var LSValues = this.gamepad.leftStick;
  72048. if (LSValues && LSValues.y != 0) {
  72049. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72050. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  72051. this.camera.inertialRadiusOffset -= normalizedLY;
  72052. }
  72053. }
  72054. }
  72055. };
  72056. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  72057. return "ArcRotateCameraGamepadInput";
  72058. };
  72059. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  72060. return "gamepad";
  72061. };
  72062. __decorate([
  72063. BABYLON.serialize()
  72064. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  72065. __decorate([
  72066. BABYLON.serialize()
  72067. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72068. return ArcRotateCameraGamepadInput;
  72069. }());
  72070. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  72071. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  72072. })(BABYLON || (BABYLON = {}));
  72073. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  72074. var BABYLON;
  72075. (function (BABYLON) {
  72076. var GamepadManager = /** @class */ (function () {
  72077. function GamepadManager(_scene) {
  72078. var _this = this;
  72079. this._scene = _scene;
  72080. this._babylonGamepads = [];
  72081. this._oneGamepadConnected = false;
  72082. this._isMonitoring = false;
  72083. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  72084. if (!BABYLON.Tools.IsWindowObjectExist()) {
  72085. this._gamepadEventSupported = false;
  72086. }
  72087. else {
  72088. this._gamepadEventSupported = 'GamepadEvent' in window;
  72089. this._gamepadSupport = (navigator.getGamepads ||
  72090. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  72091. }
  72092. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  72093. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  72094. for (var i in _this._babylonGamepads) {
  72095. var gamepad = _this._babylonGamepads[i];
  72096. if (gamepad && gamepad._isConnected) {
  72097. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  72098. }
  72099. }
  72100. });
  72101. this._onGamepadConnectedEvent = function (evt) {
  72102. var gamepad = evt.gamepad;
  72103. if (gamepad.index in _this._babylonGamepads) {
  72104. if (_this._babylonGamepads[gamepad.index].isConnected) {
  72105. return;
  72106. }
  72107. }
  72108. var newGamepad;
  72109. if (_this._babylonGamepads[gamepad.index]) {
  72110. newGamepad = _this._babylonGamepads[gamepad.index];
  72111. newGamepad.browserGamepad = gamepad;
  72112. newGamepad._isConnected = true;
  72113. }
  72114. else {
  72115. newGamepad = _this._addNewGamepad(gamepad);
  72116. }
  72117. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72118. _this._startMonitoringGamepads();
  72119. };
  72120. this._onGamepadDisconnectedEvent = function (evt) {
  72121. var gamepad = evt.gamepad;
  72122. // Remove the gamepad from the list of gamepads to monitor.
  72123. for (var i in _this._babylonGamepads) {
  72124. if (_this._babylonGamepads[i].index === gamepad.index) {
  72125. var disconnectedGamepad = _this._babylonGamepads[i];
  72126. disconnectedGamepad._isConnected = false;
  72127. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  72128. break;
  72129. }
  72130. }
  72131. };
  72132. if (this._gamepadSupport) {
  72133. //first add already-connected gamepads
  72134. this._updateGamepadObjects();
  72135. if (this._babylonGamepads.length) {
  72136. this._startMonitoringGamepads();
  72137. }
  72138. // Checking if the gamepad connected event is supported (like in Firefox)
  72139. if (this._gamepadEventSupported) {
  72140. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  72141. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  72142. }
  72143. else {
  72144. this._startMonitoringGamepads();
  72145. }
  72146. }
  72147. }
  72148. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  72149. get: function () {
  72150. return this._babylonGamepads;
  72151. },
  72152. enumerable: true,
  72153. configurable: true
  72154. });
  72155. GamepadManager.prototype.getGamepadByType = function (type) {
  72156. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  72157. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  72158. var gamepad = _a[_i];
  72159. if (gamepad && gamepad.type === type) {
  72160. return gamepad;
  72161. }
  72162. }
  72163. return null;
  72164. };
  72165. GamepadManager.prototype.dispose = function () {
  72166. if (this._gamepadEventSupported) {
  72167. if (this._onGamepadConnectedEvent) {
  72168. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  72169. }
  72170. if (this._onGamepadDisconnectedEvent) {
  72171. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  72172. }
  72173. this._onGamepadConnectedEvent = null;
  72174. this._onGamepadDisconnectedEvent = null;
  72175. }
  72176. this._babylonGamepads.forEach(function (gamepad) {
  72177. gamepad.dispose();
  72178. });
  72179. this.onGamepadConnectedObservable.clear();
  72180. this.onGamepadDisconnectedObservable.clear();
  72181. this._oneGamepadConnected = false;
  72182. this._stopMonitoringGamepads();
  72183. this._babylonGamepads = [];
  72184. };
  72185. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  72186. if (!this._oneGamepadConnected) {
  72187. this._oneGamepadConnected = true;
  72188. }
  72189. var newGamepad;
  72190. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  72191. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  72192. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  72193. }
  72194. // if pose is supported, use the (WebVR) pose enabled controller
  72195. else if (gamepad.pose) {
  72196. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  72197. }
  72198. else {
  72199. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  72200. }
  72201. this._babylonGamepads[newGamepad.index] = newGamepad;
  72202. return newGamepad;
  72203. };
  72204. GamepadManager.prototype._startMonitoringGamepads = function () {
  72205. if (!this._isMonitoring) {
  72206. this._isMonitoring = true;
  72207. //back-comp
  72208. if (!this._scene) {
  72209. this._checkGamepadsStatus();
  72210. }
  72211. }
  72212. };
  72213. GamepadManager.prototype._stopMonitoringGamepads = function () {
  72214. this._isMonitoring = false;
  72215. };
  72216. GamepadManager.prototype._checkGamepadsStatus = function () {
  72217. var _this = this;
  72218. // Hack to be compatible Chrome
  72219. this._updateGamepadObjects();
  72220. for (var i in this._babylonGamepads) {
  72221. var gamepad = this._babylonGamepads[i];
  72222. if (!gamepad || !gamepad.isConnected) {
  72223. continue;
  72224. }
  72225. gamepad.update();
  72226. }
  72227. if (this._isMonitoring && !this._scene) {
  72228. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  72229. }
  72230. };
  72231. // This function is called only on Chrome, which does not properly support
  72232. // connection/disconnection events and forces you to recopy again the gamepad object
  72233. GamepadManager.prototype._updateGamepadObjects = function () {
  72234. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  72235. for (var i = 0; i < gamepads.length; i++) {
  72236. var gamepad = gamepads[i];
  72237. if (gamepad) {
  72238. if (!this._babylonGamepads[gamepad.index]) {
  72239. var newGamepad = this._addNewGamepad(gamepad);
  72240. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72241. }
  72242. else {
  72243. // Forced to copy again this object for Chrome for unknown reason
  72244. this._babylonGamepads[i].browserGamepad = gamepad;
  72245. if (!this._babylonGamepads[i].isConnected) {
  72246. this._babylonGamepads[i]._isConnected = true;
  72247. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  72248. }
  72249. }
  72250. }
  72251. }
  72252. };
  72253. return GamepadManager;
  72254. }());
  72255. BABYLON.GamepadManager = GamepadManager;
  72256. })(BABYLON || (BABYLON = {}));
  72257. //# sourceMappingURL=babylon.gamepadManager.js.map
  72258. var BABYLON;
  72259. (function (BABYLON) {
  72260. var StickValues = /** @class */ (function () {
  72261. function StickValues(x, y) {
  72262. this.x = x;
  72263. this.y = y;
  72264. }
  72265. return StickValues;
  72266. }());
  72267. BABYLON.StickValues = StickValues;
  72268. var Gamepad = /** @class */ (function () {
  72269. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  72270. if (leftStickX === void 0) { leftStickX = 0; }
  72271. if (leftStickY === void 0) { leftStickY = 1; }
  72272. if (rightStickX === void 0) { rightStickX = 2; }
  72273. if (rightStickY === void 0) { rightStickY = 3; }
  72274. this.id = id;
  72275. this.index = index;
  72276. this.browserGamepad = browserGamepad;
  72277. this._isConnected = true;
  72278. this._invertLeftStickY = false;
  72279. this.type = Gamepad.GAMEPAD;
  72280. this._leftStickAxisX = leftStickX;
  72281. this._leftStickAxisY = leftStickY;
  72282. this._rightStickAxisX = rightStickX;
  72283. this._rightStickAxisY = rightStickY;
  72284. if (this.browserGamepad.axes.length >= 2) {
  72285. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72286. }
  72287. if (this.browserGamepad.axes.length >= 4) {
  72288. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72289. }
  72290. }
  72291. Object.defineProperty(Gamepad.prototype, "isConnected", {
  72292. get: function () {
  72293. return this._isConnected;
  72294. },
  72295. enumerable: true,
  72296. configurable: true
  72297. });
  72298. Gamepad.prototype.onleftstickchanged = function (callback) {
  72299. this._onleftstickchanged = callback;
  72300. };
  72301. Gamepad.prototype.onrightstickchanged = function (callback) {
  72302. this._onrightstickchanged = callback;
  72303. };
  72304. Object.defineProperty(Gamepad.prototype, "leftStick", {
  72305. get: function () {
  72306. return this._leftStick;
  72307. },
  72308. set: function (newValues) {
  72309. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  72310. this._onleftstickchanged(newValues);
  72311. }
  72312. this._leftStick = newValues;
  72313. },
  72314. enumerable: true,
  72315. configurable: true
  72316. });
  72317. Object.defineProperty(Gamepad.prototype, "rightStick", {
  72318. get: function () {
  72319. return this._rightStick;
  72320. },
  72321. set: function (newValues) {
  72322. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  72323. this._onrightstickchanged(newValues);
  72324. }
  72325. this._rightStick = newValues;
  72326. },
  72327. enumerable: true,
  72328. configurable: true
  72329. });
  72330. Gamepad.prototype.update = function () {
  72331. if (this._leftStick) {
  72332. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72333. if (this._invertLeftStickY) {
  72334. this.leftStick.y *= -1;
  72335. }
  72336. }
  72337. if (this._rightStick) {
  72338. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72339. }
  72340. };
  72341. Gamepad.prototype.dispose = function () {
  72342. };
  72343. Gamepad.GAMEPAD = 0;
  72344. Gamepad.GENERIC = 1;
  72345. Gamepad.XBOX = 2;
  72346. Gamepad.POSE_ENABLED = 3;
  72347. return Gamepad;
  72348. }());
  72349. BABYLON.Gamepad = Gamepad;
  72350. var GenericPad = /** @class */ (function (_super) {
  72351. __extends(GenericPad, _super);
  72352. function GenericPad(id, index, browserGamepad) {
  72353. var _this = _super.call(this, id, index, browserGamepad) || this;
  72354. _this.onButtonDownObservable = new BABYLON.Observable();
  72355. _this.onButtonUpObservable = new BABYLON.Observable();
  72356. _this.type = Gamepad.GENERIC;
  72357. _this._buttons = new Array(browserGamepad.buttons.length);
  72358. return _this;
  72359. }
  72360. GenericPad.prototype.onbuttondown = function (callback) {
  72361. this._onbuttondown = callback;
  72362. };
  72363. GenericPad.prototype.onbuttonup = function (callback) {
  72364. this._onbuttonup = callback;
  72365. };
  72366. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  72367. if (newValue !== currentValue) {
  72368. if (newValue === 1) {
  72369. if (this._onbuttondown) {
  72370. this._onbuttondown(buttonIndex);
  72371. }
  72372. this.onButtonDownObservable.notifyObservers(buttonIndex);
  72373. }
  72374. if (newValue === 0) {
  72375. if (this._onbuttonup) {
  72376. this._onbuttonup(buttonIndex);
  72377. }
  72378. this.onButtonUpObservable.notifyObservers(buttonIndex);
  72379. }
  72380. }
  72381. return newValue;
  72382. };
  72383. GenericPad.prototype.update = function () {
  72384. _super.prototype.update.call(this);
  72385. for (var index = 0; index < this._buttons.length; index++) {
  72386. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  72387. }
  72388. };
  72389. GenericPad.prototype.dispose = function () {
  72390. _super.prototype.dispose.call(this);
  72391. this.onButtonDownObservable.clear();
  72392. this.onButtonUpObservable.clear();
  72393. };
  72394. return GenericPad;
  72395. }(Gamepad));
  72396. BABYLON.GenericPad = GenericPad;
  72397. })(BABYLON || (BABYLON = {}));
  72398. //# sourceMappingURL=babylon.gamepad.js.map
  72399. var BABYLON;
  72400. (function (BABYLON) {
  72401. /**
  72402. * Defines supported buttons for XBox360 compatible gamepads
  72403. */
  72404. var Xbox360Button;
  72405. (function (Xbox360Button) {
  72406. /** A */
  72407. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  72408. /** B */
  72409. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  72410. /** X */
  72411. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  72412. /** Y */
  72413. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  72414. /** Start */
  72415. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  72416. /** Back */
  72417. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  72418. /** Left button */
  72419. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  72420. /** Right button */
  72421. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  72422. /** Left stick */
  72423. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  72424. /** Right stick */
  72425. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  72426. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  72427. /** Defines values for XBox360 DPad */
  72428. var Xbox360Dpad;
  72429. (function (Xbox360Dpad) {
  72430. /** Up */
  72431. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  72432. /** Down */
  72433. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  72434. /** Left */
  72435. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  72436. /** Right */
  72437. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  72438. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  72439. /**
  72440. * Defines a XBox360 gamepad
  72441. */
  72442. var Xbox360Pad = /** @class */ (function (_super) {
  72443. __extends(Xbox360Pad, _super);
  72444. /**
  72445. * Creates a new XBox360 gamepad object
  72446. * @param id defines the id of this gamepad
  72447. * @param index defines its index
  72448. * @param gamepad defines the internal HTML gamepad object
  72449. * @param xboxOne defines if it is a XBox One gamepad
  72450. */
  72451. function Xbox360Pad(id, index, gamepad, xboxOne) {
  72452. if (xboxOne === void 0) { xboxOne = false; }
  72453. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  72454. _this._leftTrigger = 0;
  72455. _this._rightTrigger = 0;
  72456. /** Observable raised when a button is pressed */
  72457. _this.onButtonDownObservable = new BABYLON.Observable();
  72458. /** Observable raised when a button is released */
  72459. _this.onButtonUpObservable = new BABYLON.Observable();
  72460. /** Observable raised when a pad is pressed */
  72461. _this.onPadDownObservable = new BABYLON.Observable();
  72462. /** Observable raised when a pad is released */
  72463. _this.onPadUpObservable = new BABYLON.Observable();
  72464. _this._buttonA = 0;
  72465. _this._buttonB = 0;
  72466. _this._buttonX = 0;
  72467. _this._buttonY = 0;
  72468. _this._buttonBack = 0;
  72469. _this._buttonStart = 0;
  72470. _this._buttonLB = 0;
  72471. _this._buttonRB = 0;
  72472. _this._buttonLeftStick = 0;
  72473. _this._buttonRightStick = 0;
  72474. _this._dPadUp = 0;
  72475. _this._dPadDown = 0;
  72476. _this._dPadLeft = 0;
  72477. _this._dPadRight = 0;
  72478. _this._isXboxOnePad = false;
  72479. _this.type = BABYLON.Gamepad.XBOX;
  72480. _this._isXboxOnePad = xboxOne;
  72481. return _this;
  72482. }
  72483. /**
  72484. * Defines the callback to call when left trigger is pressed
  72485. * @param callback defines the callback to use
  72486. */
  72487. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  72488. this._onlefttriggerchanged = callback;
  72489. };
  72490. /**
  72491. * Defines the callback to call when right trigger is pressed
  72492. * @param callback defines the callback to use
  72493. */
  72494. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  72495. this._onrighttriggerchanged = callback;
  72496. };
  72497. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  72498. /**
  72499. * Gets or sets left trigger value
  72500. */
  72501. get: function () {
  72502. return this._leftTrigger;
  72503. },
  72504. set: function (newValue) {
  72505. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  72506. this._onlefttriggerchanged(newValue);
  72507. }
  72508. this._leftTrigger = newValue;
  72509. },
  72510. enumerable: true,
  72511. configurable: true
  72512. });
  72513. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  72514. /**
  72515. * Gets or sets right trigger value
  72516. */
  72517. get: function () {
  72518. return this._rightTrigger;
  72519. },
  72520. set: function (newValue) {
  72521. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  72522. this._onrighttriggerchanged(newValue);
  72523. }
  72524. this._rightTrigger = newValue;
  72525. },
  72526. enumerable: true,
  72527. configurable: true
  72528. });
  72529. /**
  72530. * Defines the callback to call when a button is pressed
  72531. * @param callback defines the callback to use
  72532. */
  72533. Xbox360Pad.prototype.onbuttondown = function (callback) {
  72534. this._onbuttondown = callback;
  72535. };
  72536. /**
  72537. * Defines the callback to call when a button is released
  72538. * @param callback defines the callback to use
  72539. */
  72540. Xbox360Pad.prototype.onbuttonup = function (callback) {
  72541. this._onbuttonup = callback;
  72542. };
  72543. /**
  72544. * Defines the callback to call when a pad is pressed
  72545. * @param callback defines the callback to use
  72546. */
  72547. Xbox360Pad.prototype.ondpaddown = function (callback) {
  72548. this._ondpaddown = callback;
  72549. };
  72550. /**
  72551. * Defines the callback to call when a pad is released
  72552. * @param callback defines the callback to use
  72553. */
  72554. Xbox360Pad.prototype.ondpadup = function (callback) {
  72555. this._ondpadup = callback;
  72556. };
  72557. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  72558. if (newValue !== currentValue) {
  72559. if (newValue === 1) {
  72560. if (this._onbuttondown) {
  72561. this._onbuttondown(buttonType);
  72562. }
  72563. this.onButtonDownObservable.notifyObservers(buttonType);
  72564. }
  72565. if (newValue === 0) {
  72566. if (this._onbuttonup) {
  72567. this._onbuttonup(buttonType);
  72568. }
  72569. this.onButtonUpObservable.notifyObservers(buttonType);
  72570. }
  72571. }
  72572. return newValue;
  72573. };
  72574. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  72575. if (newValue !== currentValue) {
  72576. if (newValue === 1) {
  72577. if (this._ondpaddown) {
  72578. this._ondpaddown(buttonType);
  72579. }
  72580. this.onPadDownObservable.notifyObservers(buttonType);
  72581. }
  72582. if (newValue === 0) {
  72583. if (this._ondpadup) {
  72584. this._ondpadup(buttonType);
  72585. }
  72586. this.onPadUpObservable.notifyObservers(buttonType);
  72587. }
  72588. }
  72589. return newValue;
  72590. };
  72591. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  72592. /** Gets or sets value of A button */
  72593. get: function () {
  72594. return this._buttonA;
  72595. },
  72596. set: function (value) {
  72597. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  72598. },
  72599. enumerable: true,
  72600. configurable: true
  72601. });
  72602. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  72603. /** Gets or sets value of B button */
  72604. get: function () {
  72605. return this._buttonB;
  72606. },
  72607. set: function (value) {
  72608. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  72609. },
  72610. enumerable: true,
  72611. configurable: true
  72612. });
  72613. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  72614. /** Gets or sets value of X button */
  72615. get: function () {
  72616. return this._buttonX;
  72617. },
  72618. set: function (value) {
  72619. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  72620. },
  72621. enumerable: true,
  72622. configurable: true
  72623. });
  72624. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  72625. /** Gets or sets value of Y button */
  72626. get: function () {
  72627. return this._buttonY;
  72628. },
  72629. set: function (value) {
  72630. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  72631. },
  72632. enumerable: true,
  72633. configurable: true
  72634. });
  72635. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  72636. /** Gets or sets value of Start button */
  72637. get: function () {
  72638. return this._buttonStart;
  72639. },
  72640. set: function (value) {
  72641. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  72642. },
  72643. enumerable: true,
  72644. configurable: true
  72645. });
  72646. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  72647. /** Gets or sets value of Back button */
  72648. get: function () {
  72649. return this._buttonBack;
  72650. },
  72651. set: function (value) {
  72652. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  72653. },
  72654. enumerable: true,
  72655. configurable: true
  72656. });
  72657. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  72658. /** Gets or sets value of Left button */
  72659. get: function () {
  72660. return this._buttonLB;
  72661. },
  72662. set: function (value) {
  72663. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  72664. },
  72665. enumerable: true,
  72666. configurable: true
  72667. });
  72668. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  72669. /** Gets or sets value of Right button */
  72670. get: function () {
  72671. return this._buttonRB;
  72672. },
  72673. set: function (value) {
  72674. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  72675. },
  72676. enumerable: true,
  72677. configurable: true
  72678. });
  72679. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  72680. /** Gets or sets value of left stick */
  72681. get: function () {
  72682. return this._buttonLeftStick;
  72683. },
  72684. set: function (value) {
  72685. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  72686. },
  72687. enumerable: true,
  72688. configurable: true
  72689. });
  72690. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  72691. /** Gets or sets value of right stick */
  72692. get: function () {
  72693. return this._buttonRightStick;
  72694. },
  72695. set: function (value) {
  72696. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  72697. },
  72698. enumerable: true,
  72699. configurable: true
  72700. });
  72701. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  72702. /** Gets or sets value of DPad up */
  72703. get: function () {
  72704. return this._dPadUp;
  72705. },
  72706. set: function (value) {
  72707. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  72708. },
  72709. enumerable: true,
  72710. configurable: true
  72711. });
  72712. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  72713. /** Gets or sets value of DPad down */
  72714. get: function () {
  72715. return this._dPadDown;
  72716. },
  72717. set: function (value) {
  72718. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  72719. },
  72720. enumerable: true,
  72721. configurable: true
  72722. });
  72723. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  72724. /** Gets or sets value of DPad left */
  72725. get: function () {
  72726. return this._dPadLeft;
  72727. },
  72728. set: function (value) {
  72729. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  72730. },
  72731. enumerable: true,
  72732. configurable: true
  72733. });
  72734. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  72735. /** Gets or sets value of DPad right */
  72736. get: function () {
  72737. return this._dPadRight;
  72738. },
  72739. set: function (value) {
  72740. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  72741. },
  72742. enumerable: true,
  72743. configurable: true
  72744. });
  72745. /**
  72746. * Force the gamepad to synchronize with device values
  72747. */
  72748. Xbox360Pad.prototype.update = function () {
  72749. _super.prototype.update.call(this);
  72750. if (this._isXboxOnePad) {
  72751. this.buttonA = this.browserGamepad.buttons[0].value;
  72752. this.buttonB = this.browserGamepad.buttons[1].value;
  72753. this.buttonX = this.browserGamepad.buttons[2].value;
  72754. this.buttonY = this.browserGamepad.buttons[3].value;
  72755. this.buttonLB = this.browserGamepad.buttons[4].value;
  72756. this.buttonRB = this.browserGamepad.buttons[5].value;
  72757. this.leftTrigger = this.browserGamepad.axes[2];
  72758. this.rightTrigger = this.browserGamepad.axes[5];
  72759. this.buttonBack = this.browserGamepad.buttons[9].value;
  72760. this.buttonStart = this.browserGamepad.buttons[8].value;
  72761. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  72762. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  72763. this.dPadUp = this.browserGamepad.buttons[11].value;
  72764. this.dPadDown = this.browserGamepad.buttons[12].value;
  72765. this.dPadLeft = this.browserGamepad.buttons[13].value;
  72766. this.dPadRight = this.browserGamepad.buttons[14].value;
  72767. }
  72768. else {
  72769. this.buttonA = this.browserGamepad.buttons[0].value;
  72770. this.buttonB = this.browserGamepad.buttons[1].value;
  72771. this.buttonX = this.browserGamepad.buttons[2].value;
  72772. this.buttonY = this.browserGamepad.buttons[3].value;
  72773. this.buttonLB = this.browserGamepad.buttons[4].value;
  72774. this.buttonRB = this.browserGamepad.buttons[5].value;
  72775. this.leftTrigger = this.browserGamepad.buttons[6].value;
  72776. this.rightTrigger = this.browserGamepad.buttons[7].value;
  72777. this.buttonBack = this.browserGamepad.buttons[8].value;
  72778. this.buttonStart = this.browserGamepad.buttons[9].value;
  72779. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  72780. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  72781. this.dPadUp = this.browserGamepad.buttons[12].value;
  72782. this.dPadDown = this.browserGamepad.buttons[13].value;
  72783. this.dPadLeft = this.browserGamepad.buttons[14].value;
  72784. this.dPadRight = this.browserGamepad.buttons[15].value;
  72785. }
  72786. };
  72787. Xbox360Pad.prototype.dispose = function () {
  72788. _super.prototype.dispose.call(this);
  72789. this.onButtonDownObservable.clear();
  72790. this.onButtonUpObservable.clear();
  72791. this.onPadDownObservable.clear();
  72792. this.onPadUpObservable.clear();
  72793. };
  72794. return Xbox360Pad;
  72795. }(BABYLON.Gamepad));
  72796. BABYLON.Xbox360Pad = Xbox360Pad;
  72797. })(BABYLON || (BABYLON = {}));
  72798. //# sourceMappingURL=babylon.xboxGamepad.js.map
  72799. var BABYLON;
  72800. (function (BABYLON) {
  72801. /**
  72802. * Defines the types of pose enabled controllers that are supported
  72803. */
  72804. var PoseEnabledControllerType;
  72805. (function (PoseEnabledControllerType) {
  72806. /**
  72807. * HTC Vive
  72808. */
  72809. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  72810. /**
  72811. * Oculus Rift
  72812. */
  72813. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  72814. /**
  72815. * Windows mixed reality
  72816. */
  72817. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  72818. /**
  72819. * Samsung gear VR
  72820. */
  72821. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  72822. /**
  72823. * Google Daydream
  72824. */
  72825. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  72826. /**
  72827. * Generic
  72828. */
  72829. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  72830. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  72831. /**
  72832. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72833. */
  72834. var PoseEnabledControllerHelper = /** @class */ (function () {
  72835. function PoseEnabledControllerHelper() {
  72836. }
  72837. /**
  72838. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72839. * @param vrGamepad the gamepad to initialized
  72840. * @returns a vr controller of the type the gamepad identified as
  72841. */
  72842. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  72843. // Oculus Touch
  72844. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  72845. return new BABYLON.OculusTouchController(vrGamepad);
  72846. }
  72847. // Windows Mixed Reality controllers
  72848. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  72849. return new BABYLON.WindowsMotionController(vrGamepad);
  72850. }
  72851. // HTC Vive
  72852. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  72853. return new BABYLON.ViveController(vrGamepad);
  72854. }
  72855. // Samsung/Oculus Gear VR or Oculus Go
  72856. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  72857. return new BABYLON.GearVRController(vrGamepad);
  72858. }
  72859. // Google Daydream
  72860. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  72861. return new BABYLON.DaydreamController(vrGamepad);
  72862. }
  72863. // Generic
  72864. else {
  72865. return new BABYLON.GenericController(vrGamepad);
  72866. }
  72867. };
  72868. return PoseEnabledControllerHelper;
  72869. }());
  72870. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  72871. /**
  72872. * Defines the PoseEnabledController object that contains state of a vr capable controller
  72873. */
  72874. var PoseEnabledController = /** @class */ (function (_super) {
  72875. __extends(PoseEnabledController, _super);
  72876. /**
  72877. * Creates a new PoseEnabledController from a gamepad
  72878. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  72879. */
  72880. function PoseEnabledController(browserGamepad) {
  72881. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  72882. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72883. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72884. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  72885. /**
  72886. * The device position in babylon space
  72887. */
  72888. _this.devicePosition = BABYLON.Vector3.Zero();
  72889. /**
  72890. * The device rotation in babylon space
  72891. */
  72892. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  72893. /**
  72894. * The scale factor of the device in babylon space
  72895. */
  72896. _this.deviceScaleFactor = 1;
  72897. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  72898. /**
  72899. * Internal, matrix used to convert room space to babylon space
  72900. */
  72901. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72902. /**
  72903. * Node to be used when casting a ray from the controller
  72904. */
  72905. _this._pointingPoseNode = null;
  72906. _this._workingMatrix = BABYLON.Matrix.Identity();
  72907. /**
  72908. * @hidden
  72909. */
  72910. _this._meshAttachedObservable = new BABYLON.Observable();
  72911. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  72912. _this.controllerType = PoseEnabledControllerType.GENERIC;
  72913. _this.position = BABYLON.Vector3.Zero();
  72914. _this.rotationQuaternion = new BABYLON.Quaternion();
  72915. _this._calculatedPosition = BABYLON.Vector3.Zero();
  72916. _this._calculatedRotation = new BABYLON.Quaternion();
  72917. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  72918. return _this;
  72919. }
  72920. /**
  72921. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  72922. */
  72923. PoseEnabledController.prototype.update = function () {
  72924. _super.prototype.update.call(this);
  72925. this._updatePoseAndMesh();
  72926. };
  72927. /**
  72928. * Updates only the pose device and mesh without doing any button event checking
  72929. */
  72930. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  72931. var pose = this.browserGamepad.pose;
  72932. this.updateFromDevice(pose);
  72933. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  72934. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  72935. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72936. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  72937. if (this._mesh) {
  72938. this._mesh.position.copyFrom(this.devicePosition);
  72939. if (this._mesh.rotationQuaternion) {
  72940. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  72941. }
  72942. }
  72943. };
  72944. /**
  72945. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  72946. * @param poseData raw pose fromthe device
  72947. */
  72948. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  72949. if (poseData) {
  72950. this.rawPose = poseData;
  72951. if (poseData.position) {
  72952. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  72953. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  72954. this._deviceRoomPosition.z *= -1;
  72955. }
  72956. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  72957. this._calculatedPosition.addInPlace(this.position);
  72958. }
  72959. var pose = this.rawPose;
  72960. if (poseData.orientation && pose.orientation) {
  72961. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  72962. if (this._mesh) {
  72963. if (this._mesh.getScene().useRightHandedSystem) {
  72964. this._deviceRoomRotationQuaternion.z *= -1;
  72965. this._deviceRoomRotationQuaternion.w *= -1;
  72966. }
  72967. else {
  72968. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  72969. }
  72970. }
  72971. // if the camera is set, rotate to the camera's rotation
  72972. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  72973. }
  72974. }
  72975. };
  72976. /**
  72977. * Attaches a mesh to the controller
  72978. * @param mesh the mesh to be attached
  72979. */
  72980. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  72981. if (this._mesh) {
  72982. this._mesh.parent = null;
  72983. }
  72984. this._mesh = mesh;
  72985. if (this._poseControlledCamera) {
  72986. this._mesh.parent = this._poseControlledCamera;
  72987. }
  72988. if (!this._mesh.rotationQuaternion) {
  72989. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  72990. }
  72991. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  72992. this._updatePoseAndMesh();
  72993. if (this._pointingPoseNode) {
  72994. var parents = [];
  72995. var obj = this._pointingPoseNode;
  72996. while (obj.parent) {
  72997. parents.push(obj.parent);
  72998. obj = obj.parent;
  72999. }
  73000. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  73001. }
  73002. this._meshAttachedObservable.notifyObservers(mesh);
  73003. };
  73004. /**
  73005. * Attaches the controllers mesh to a camera
  73006. * @param camera the camera the mesh should be attached to
  73007. */
  73008. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  73009. this._poseControlledCamera = camera;
  73010. if (this._mesh) {
  73011. this._mesh.parent = this._poseControlledCamera;
  73012. }
  73013. };
  73014. /**
  73015. * Disposes of the controller
  73016. */
  73017. PoseEnabledController.prototype.dispose = function () {
  73018. if (this._mesh) {
  73019. this._mesh.dispose();
  73020. }
  73021. this._mesh = null;
  73022. _super.prototype.dispose.call(this);
  73023. };
  73024. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  73025. /**
  73026. * The mesh that is attached to the controller
  73027. */
  73028. get: function () {
  73029. return this._mesh;
  73030. },
  73031. enumerable: true,
  73032. configurable: true
  73033. });
  73034. /**
  73035. * Gets the ray of the controller in the direction the controller is pointing
  73036. * @param length the length the resulting ray should be
  73037. * @returns a ray in the direction the controller is pointing
  73038. */
  73039. PoseEnabledController.prototype.getForwardRay = function (length) {
  73040. if (length === void 0) { length = 100; }
  73041. if (!this.mesh) {
  73042. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  73043. }
  73044. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  73045. var origin = m.getTranslation();
  73046. var forward = new BABYLON.Vector3(0, 0, -1);
  73047. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73048. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73049. return new BABYLON.Ray(origin, direction, length);
  73050. };
  73051. /**
  73052. * Name of the child mesh that can be used to cast a ray from the controller
  73053. */
  73054. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  73055. return PoseEnabledController;
  73056. }(BABYLON.Gamepad));
  73057. BABYLON.PoseEnabledController = PoseEnabledController;
  73058. })(BABYLON || (BABYLON = {}));
  73059. //# sourceMappingURL=babylon.poseEnabledController.js.map
  73060. var BABYLON;
  73061. (function (BABYLON) {
  73062. /**
  73063. * Defines the WebVRController object that represents controllers tracked in 3D space
  73064. */
  73065. var WebVRController = /** @class */ (function (_super) {
  73066. __extends(WebVRController, _super);
  73067. /**
  73068. * Creates a new WebVRController from a gamepad
  73069. * @param vrGamepad the gamepad that the WebVRController should be created from
  73070. */
  73071. function WebVRController(vrGamepad) {
  73072. var _this = _super.call(this, vrGamepad) || this;
  73073. // Observables
  73074. /**
  73075. * Fired when the trigger state has changed
  73076. */
  73077. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  73078. /**
  73079. * Fired when the main button state has changed
  73080. */
  73081. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  73082. /**
  73083. * Fired when the secondary button state has changed
  73084. */
  73085. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  73086. /**
  73087. * Fired when the pad state has changed
  73088. */
  73089. _this.onPadStateChangedObservable = new BABYLON.Observable();
  73090. /**
  73091. * Fired when controllers stick values have changed
  73092. */
  73093. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  73094. /**
  73095. * X and Y axis corrisponding to the controllers joystick
  73096. */
  73097. _this.pad = { x: 0, y: 0 };
  73098. // avoid GC, store state in a tmp object
  73099. _this._changes = {
  73100. pressChanged: false,
  73101. touchChanged: false,
  73102. valueChanged: false,
  73103. changed: false
  73104. };
  73105. _this._buttons = new Array(vrGamepad.buttons.length);
  73106. _this.hand = vrGamepad.hand;
  73107. return _this;
  73108. }
  73109. /**
  73110. * Fired when a controller button's state has changed
  73111. * @param callback the callback containing the button that was modified
  73112. */
  73113. WebVRController.prototype.onButtonStateChange = function (callback) {
  73114. this._onButtonStateChange = callback;
  73115. };
  73116. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  73117. /**
  73118. * The default controller model for the controller
  73119. */
  73120. get: function () {
  73121. return this._defaultModel;
  73122. },
  73123. enumerable: true,
  73124. configurable: true
  73125. });
  73126. /**
  73127. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  73128. */
  73129. WebVRController.prototype.update = function () {
  73130. _super.prototype.update.call(this);
  73131. for (var index = 0; index < this._buttons.length; index++) {
  73132. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  73133. }
  73134. ;
  73135. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  73136. this.pad.x = this.leftStick.x;
  73137. this.pad.y = this.leftStick.y;
  73138. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  73139. }
  73140. };
  73141. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  73142. if (!newState) {
  73143. newState = {
  73144. pressed: false,
  73145. touched: false,
  73146. value: 0
  73147. };
  73148. }
  73149. if (!currentState) {
  73150. this._buttons[buttonIndex] = {
  73151. pressed: newState.pressed,
  73152. touched: newState.touched,
  73153. value: newState.value
  73154. };
  73155. return;
  73156. }
  73157. this._checkChanges(newState, currentState);
  73158. if (this._changes.changed) {
  73159. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  73160. this._handleButtonChange(buttonIndex, newState, this._changes);
  73161. }
  73162. this._buttons[buttonIndex].pressed = newState.pressed;
  73163. this._buttons[buttonIndex].touched = newState.touched;
  73164. // oculus triggers are never 0, thou not touched.
  73165. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  73166. };
  73167. WebVRController.prototype._checkChanges = function (newState, currentState) {
  73168. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  73169. this._changes.touchChanged = newState.touched !== currentState.touched;
  73170. this._changes.valueChanged = newState.value !== currentState.value;
  73171. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  73172. return this._changes;
  73173. };
  73174. /**
  73175. * Disposes of th webVRCOntroller
  73176. */
  73177. WebVRController.prototype.dispose = function () {
  73178. _super.prototype.dispose.call(this);
  73179. this.onTriggerStateChangedObservable.clear();
  73180. this.onMainButtonStateChangedObservable.clear();
  73181. this.onSecondaryButtonStateChangedObservable.clear();
  73182. this.onPadStateChangedObservable.clear();
  73183. this.onPadValuesChangedObservable.clear();
  73184. };
  73185. return WebVRController;
  73186. }(BABYLON.PoseEnabledController));
  73187. BABYLON.WebVRController = WebVRController;
  73188. })(BABYLON || (BABYLON = {}));
  73189. //# sourceMappingURL=babylon.webVRController.js.map
  73190. var BABYLON;
  73191. (function (BABYLON) {
  73192. /**
  73193. * Oculus Touch Controller
  73194. */
  73195. var OculusTouchController = /** @class */ (function (_super) {
  73196. __extends(OculusTouchController, _super);
  73197. /**
  73198. * Creates a new OculusTouchController from a gamepad
  73199. * @param vrGamepad the gamepad that the controller should be created from
  73200. */
  73201. function OculusTouchController(vrGamepad) {
  73202. var _this = _super.call(this, vrGamepad) || this;
  73203. /**
  73204. * Fired when the secondary trigger on this controller is modified
  73205. */
  73206. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  73207. /**
  73208. * Fired when the thumb rest on this controller is modified
  73209. */
  73210. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  73211. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  73212. return _this;
  73213. }
  73214. /**
  73215. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73216. * @param scene scene in which to add meshes
  73217. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73218. */
  73219. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73220. var _this = this;
  73221. var meshName;
  73222. // Hand
  73223. if (this.hand === 'left') {
  73224. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  73225. }
  73226. else { // Right is the default if no hand is specified
  73227. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  73228. }
  73229. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  73230. /*
  73231. Parent Mesh name: oculus_touch_left
  73232. - body
  73233. - trigger
  73234. - thumbstick
  73235. - grip
  73236. - button_y
  73237. - button_x
  73238. - button_enter
  73239. */
  73240. _this._defaultModel = newMeshes[1];
  73241. _this.attachToMesh(_this._defaultModel);
  73242. if (meshLoaded) {
  73243. meshLoaded(_this._defaultModel);
  73244. }
  73245. });
  73246. };
  73247. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  73248. /**
  73249. * Fired when the A button on this controller is modified
  73250. */
  73251. get: function () {
  73252. if (this.hand === 'right') {
  73253. return this.onMainButtonStateChangedObservable;
  73254. }
  73255. else {
  73256. throw new Error('No A button on left hand');
  73257. }
  73258. },
  73259. enumerable: true,
  73260. configurable: true
  73261. });
  73262. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  73263. /**
  73264. * Fired when the B button on this controller is modified
  73265. */
  73266. get: function () {
  73267. if (this.hand === 'right') {
  73268. return this.onSecondaryButtonStateChangedObservable;
  73269. }
  73270. else {
  73271. throw new Error('No B button on left hand');
  73272. }
  73273. },
  73274. enumerable: true,
  73275. configurable: true
  73276. });
  73277. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  73278. /**
  73279. * Fired when the X button on this controller is modified
  73280. */
  73281. get: function () {
  73282. if (this.hand === 'left') {
  73283. return this.onMainButtonStateChangedObservable;
  73284. }
  73285. else {
  73286. throw new Error('No X button on right hand');
  73287. }
  73288. },
  73289. enumerable: true,
  73290. configurable: true
  73291. });
  73292. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  73293. /**
  73294. * Fired when the Y button on this controller is modified
  73295. */
  73296. get: function () {
  73297. if (this.hand === 'left') {
  73298. return this.onSecondaryButtonStateChangedObservable;
  73299. }
  73300. else {
  73301. throw new Error('No Y button on right hand');
  73302. }
  73303. },
  73304. enumerable: true,
  73305. configurable: true
  73306. });
  73307. /**
  73308. * Called once for each button that changed state since the last frame
  73309. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  73310. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  73311. * 2) secondary trigger (same)
  73312. * 3) A (right) X (left), touch, pressed = value
  73313. * 4) B / Y
  73314. * 5) thumb rest
  73315. * @param buttonIdx Which button index changed
  73316. * @param state New state of the button
  73317. * @param changes Which properties on the state changed since last frame
  73318. */
  73319. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73320. var notifyObject = state; //{ state: state, changes: changes };
  73321. var triggerDirection = this.hand === 'right' ? -1 : 1;
  73322. switch (buttonIdx) {
  73323. case 0:
  73324. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73325. return;
  73326. case 1: // index trigger
  73327. if (this._defaultModel) {
  73328. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  73329. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  73330. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  73331. }
  73332. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73333. return;
  73334. case 2: // secondary trigger
  73335. if (this._defaultModel) {
  73336. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  73337. }
  73338. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  73339. return;
  73340. case 3:
  73341. if (this._defaultModel) {
  73342. if (notifyObject.pressed) {
  73343. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  73344. }
  73345. else {
  73346. (this._defaultModel.getChildren()[1]).position.y = 0;
  73347. }
  73348. }
  73349. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73350. return;
  73351. case 4:
  73352. if (this._defaultModel) {
  73353. if (notifyObject.pressed) {
  73354. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73355. }
  73356. else {
  73357. (this._defaultModel.getChildren()[2]).position.y = 0;
  73358. }
  73359. }
  73360. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73361. return;
  73362. case 5:
  73363. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  73364. return;
  73365. }
  73366. };
  73367. /**
  73368. * Base Url for the controller model.
  73369. */
  73370. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  73371. /**
  73372. * File name for the left controller model.
  73373. */
  73374. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  73375. /**
  73376. * File name for the right controller model.
  73377. */
  73378. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  73379. return OculusTouchController;
  73380. }(BABYLON.WebVRController));
  73381. BABYLON.OculusTouchController = OculusTouchController;
  73382. })(BABYLON || (BABYLON = {}));
  73383. //# sourceMappingURL=babylon.oculusTouchController.js.map
  73384. var BABYLON;
  73385. (function (BABYLON) {
  73386. /**
  73387. * Vive Controller
  73388. */
  73389. var ViveController = /** @class */ (function (_super) {
  73390. __extends(ViveController, _super);
  73391. /**
  73392. * Creates a new ViveController from a gamepad
  73393. * @param vrGamepad the gamepad that the controller should be created from
  73394. */
  73395. function ViveController(vrGamepad) {
  73396. var _this = _super.call(this, vrGamepad) || this;
  73397. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  73398. _this._invertLeftStickY = true;
  73399. return _this;
  73400. }
  73401. /**
  73402. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73403. * @param scene scene in which to add meshes
  73404. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73405. */
  73406. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73407. var _this = this;
  73408. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  73409. /*
  73410. Parent Mesh name: ViveWand
  73411. - body
  73412. - r_gripper
  73413. - l_gripper
  73414. - menu_button
  73415. - system_button
  73416. - trackpad
  73417. - trigger
  73418. - LED
  73419. */
  73420. _this._defaultModel = newMeshes[1];
  73421. _this.attachToMesh(_this._defaultModel);
  73422. if (meshLoaded) {
  73423. meshLoaded(_this._defaultModel);
  73424. }
  73425. });
  73426. };
  73427. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  73428. /**
  73429. * Fired when the left button on this controller is modified
  73430. */
  73431. get: function () {
  73432. return this.onMainButtonStateChangedObservable;
  73433. },
  73434. enumerable: true,
  73435. configurable: true
  73436. });
  73437. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  73438. /**
  73439. * Fired when the right button on this controller is modified
  73440. */
  73441. get: function () {
  73442. return this.onMainButtonStateChangedObservable;
  73443. },
  73444. enumerable: true,
  73445. configurable: true
  73446. });
  73447. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  73448. /**
  73449. * Fired when the menu button on this controller is modified
  73450. */
  73451. get: function () {
  73452. return this.onSecondaryButtonStateChangedObservable;
  73453. },
  73454. enumerable: true,
  73455. configurable: true
  73456. });
  73457. /**
  73458. * Called once for each button that changed state since the last frame
  73459. * Vive mapping:
  73460. * 0: touchpad
  73461. * 1: trigger
  73462. * 2: left AND right buttons
  73463. * 3: menu button
  73464. * @param buttonIdx Which button index changed
  73465. * @param state New state of the button
  73466. * @param changes Which properties on the state changed since last frame
  73467. */
  73468. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73469. var notifyObject = state; //{ state: state, changes: changes };
  73470. switch (buttonIdx) {
  73471. case 0:
  73472. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73473. return;
  73474. case 1: // index trigger
  73475. if (this._defaultModel) {
  73476. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  73477. }
  73478. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73479. return;
  73480. case 2: // left AND right button
  73481. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73482. return;
  73483. case 3:
  73484. if (this._defaultModel) {
  73485. if (notifyObject.pressed) {
  73486. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73487. }
  73488. else {
  73489. (this._defaultModel.getChildren()[2]).position.y = 0;
  73490. }
  73491. }
  73492. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73493. return;
  73494. }
  73495. };
  73496. /**
  73497. * Base Url for the controller model.
  73498. */
  73499. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  73500. /**
  73501. * File name for the controller model.
  73502. */
  73503. ViveController.MODEL_FILENAME = 'wand.babylon';
  73504. return ViveController;
  73505. }(BABYLON.WebVRController));
  73506. BABYLON.ViveController = ViveController;
  73507. })(BABYLON || (BABYLON = {}));
  73508. //# sourceMappingURL=babylon.viveController.js.map
  73509. var BABYLON;
  73510. (function (BABYLON) {
  73511. /**
  73512. * Generic Controller
  73513. */
  73514. var GenericController = /** @class */ (function (_super) {
  73515. __extends(GenericController, _super);
  73516. /**
  73517. * Creates a new GenericController from a gamepad
  73518. * @param vrGamepad the gamepad that the controller should be created from
  73519. */
  73520. function GenericController(vrGamepad) {
  73521. return _super.call(this, vrGamepad) || this;
  73522. }
  73523. /**
  73524. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73525. * @param scene scene in which to add meshes
  73526. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73527. */
  73528. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73529. var _this = this;
  73530. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  73531. _this._defaultModel = newMeshes[1];
  73532. _this.attachToMesh(_this._defaultModel);
  73533. if (meshLoaded) {
  73534. meshLoaded(_this._defaultModel);
  73535. }
  73536. });
  73537. };
  73538. /**
  73539. * Called once for each button that changed state since the last frame
  73540. * @param buttonIdx Which button index changed
  73541. * @param state New state of the button
  73542. * @param changes Which properties on the state changed since last frame
  73543. */
  73544. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73545. console.log("Button id: " + buttonIdx + "state: ");
  73546. console.dir(state);
  73547. };
  73548. /**
  73549. * Base Url for the controller model.
  73550. */
  73551. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73552. /**
  73553. * File name for the controller model.
  73554. */
  73555. GenericController.MODEL_FILENAME = 'generic.babylon';
  73556. return GenericController;
  73557. }(BABYLON.WebVRController));
  73558. BABYLON.GenericController = GenericController;
  73559. })(BABYLON || (BABYLON = {}));
  73560. //# sourceMappingURL=babylon.genericController.js.map
  73561. var BABYLON;
  73562. (function (BABYLON) {
  73563. /**
  73564. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  73565. */
  73566. var LoadedMeshInfo = /** @class */ (function () {
  73567. function LoadedMeshInfo() {
  73568. /**
  73569. * Map of the button meshes contained in the controller
  73570. */
  73571. this.buttonMeshes = {};
  73572. /**
  73573. * Map of the axis meshes contained in the controller
  73574. */
  73575. this.axisMeshes = {};
  73576. }
  73577. return LoadedMeshInfo;
  73578. }());
  73579. /**
  73580. * Defines the WindowsMotionController object that the state of the windows motion controller
  73581. */
  73582. var WindowsMotionController = /** @class */ (function (_super) {
  73583. __extends(WindowsMotionController, _super);
  73584. /**
  73585. * Creates a new WindowsMotionController from a gamepad
  73586. * @param vrGamepad the gamepad that the controller should be created from
  73587. */
  73588. function WindowsMotionController(vrGamepad) {
  73589. var _this = _super.call(this, vrGamepad) || this;
  73590. _this._mapping = {
  73591. // Semantic button names
  73592. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  73593. // A mapping of the button name to glTF model node name
  73594. // that should be transformed by button value.
  73595. buttonMeshNames: {
  73596. 'trigger': 'SELECT',
  73597. 'menu': 'MENU',
  73598. 'grip': 'GRASP',
  73599. 'thumbstick': 'THUMBSTICK_PRESS',
  73600. 'trackpad': 'TOUCHPAD_PRESS'
  73601. },
  73602. // This mapping is used to translate from the Motion Controller to Babylon semantics
  73603. buttonObservableNames: {
  73604. 'trigger': 'onTriggerStateChangedObservable',
  73605. 'menu': 'onSecondaryButtonStateChangedObservable',
  73606. 'grip': 'onMainButtonStateChangedObservable',
  73607. 'thumbstick': 'onPadStateChangedObservable',
  73608. 'trackpad': 'onTrackpadChangedObservable'
  73609. },
  73610. // A mapping of the axis name to glTF model node name
  73611. // that should be transformed by axis value.
  73612. // This array mirrors the browserGamepad.axes array, such that
  73613. // the mesh corresponding to axis 0 is in this array index 0.
  73614. axisMeshNames: [
  73615. 'THUMBSTICK_X',
  73616. 'THUMBSTICK_Y',
  73617. 'TOUCHPAD_TOUCH_X',
  73618. 'TOUCHPAD_TOUCH_Y'
  73619. ],
  73620. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  73621. };
  73622. /**
  73623. * Fired when the trackpad on this controller is clicked
  73624. */
  73625. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  73626. /**
  73627. * Fired when the trackpad on this controller is modified
  73628. */
  73629. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  73630. /**
  73631. * The current x and y values of this controller's trackpad
  73632. */
  73633. _this.trackpad = { x: 0, y: 0 };
  73634. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  73635. _this._loadedMeshInfo = null;
  73636. return _this;
  73637. }
  73638. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  73639. /**
  73640. * Fired when the trigger on this controller is modified
  73641. */
  73642. get: function () {
  73643. return this.onTriggerStateChangedObservable;
  73644. },
  73645. enumerable: true,
  73646. configurable: true
  73647. });
  73648. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  73649. /**
  73650. * Fired when the menu button on this controller is modified
  73651. */
  73652. get: function () {
  73653. return this.onSecondaryButtonStateChangedObservable;
  73654. },
  73655. enumerable: true,
  73656. configurable: true
  73657. });
  73658. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  73659. /**
  73660. * Fired when the grip button on this controller is modified
  73661. */
  73662. get: function () {
  73663. return this.onMainButtonStateChangedObservable;
  73664. },
  73665. enumerable: true,
  73666. configurable: true
  73667. });
  73668. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  73669. /**
  73670. * Fired when the thumbstick button on this controller is modified
  73671. */
  73672. get: function () {
  73673. return this.onPadStateChangedObservable;
  73674. },
  73675. enumerable: true,
  73676. configurable: true
  73677. });
  73678. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  73679. /**
  73680. * Fired when the touchpad button on this controller is modified
  73681. */
  73682. get: function () {
  73683. return this.onTrackpadChangedObservable;
  73684. },
  73685. enumerable: true,
  73686. configurable: true
  73687. });
  73688. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  73689. /**
  73690. * Fired when the touchpad values on this controller are modified
  73691. */
  73692. get: function () {
  73693. return this.onTrackpadValuesChangedObservable;
  73694. },
  73695. enumerable: true,
  73696. configurable: true
  73697. });
  73698. WindowsMotionController.prototype._updateTrackpad = function () {
  73699. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  73700. this.trackpad.x = this.browserGamepad["axes"][2];
  73701. this.trackpad.y = this.browserGamepad["axes"][3];
  73702. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  73703. }
  73704. };
  73705. /**
  73706. * Called once per frame by the engine.
  73707. */
  73708. WindowsMotionController.prototype.update = function () {
  73709. _super.prototype.update.call(this);
  73710. if (this.browserGamepad.axes) {
  73711. this._updateTrackpad();
  73712. // Only need to animate axes if there is a loaded mesh
  73713. if (this._loadedMeshInfo) {
  73714. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  73715. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  73716. }
  73717. }
  73718. }
  73719. };
  73720. /**
  73721. * Called once for each button that changed state since the last frame
  73722. * @param buttonIdx Which button index changed
  73723. * @param state New state of the button
  73724. * @param changes Which properties on the state changed since last frame
  73725. */
  73726. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73727. var buttonName = this._mapping.buttons[buttonIdx];
  73728. if (!buttonName) {
  73729. return;
  73730. }
  73731. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  73732. this._updateTrackpad();
  73733. // Only emit events for buttons that we know how to map from index to name
  73734. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  73735. if (observable) {
  73736. observable.notifyObservers(state);
  73737. }
  73738. this._lerpButtonTransform(buttonName, state.value);
  73739. };
  73740. /**
  73741. * Moves the buttons on the controller mesh based on their current state
  73742. * @param buttonName the name of the button to move
  73743. * @param buttonValue the value of the button which determines the buttons new position
  73744. */
  73745. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  73746. // If there is no loaded mesh, there is nothing to transform.
  73747. if (!this._loadedMeshInfo) {
  73748. return;
  73749. }
  73750. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  73751. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73752. return;
  73753. }
  73754. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  73755. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  73756. };
  73757. /**
  73758. * Moves the axis on the controller mesh based on its current state
  73759. * @param axis the index of the axis
  73760. * @param axisValue the value of the axis which determines the meshes new position
  73761. * @hidden
  73762. */
  73763. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  73764. if (!this._loadedMeshInfo) {
  73765. return;
  73766. }
  73767. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  73768. if (!meshInfo) {
  73769. return;
  73770. }
  73771. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73772. return;
  73773. }
  73774. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  73775. var lerpValue = axisValue * 0.5 + 0.5;
  73776. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  73777. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  73778. };
  73779. /**
  73780. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73781. * @param scene scene in which to add meshes
  73782. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73783. */
  73784. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  73785. var _this = this;
  73786. if (forceDefault === void 0) { forceDefault = false; }
  73787. var path;
  73788. var filename;
  73789. // Checking if GLB loader is present
  73790. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  73791. // Determine the device specific folder based on the ID suffix
  73792. var device = 'default';
  73793. if (this.id && !forceDefault) {
  73794. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  73795. device = ((match && match[0]) || device);
  73796. }
  73797. // Hand
  73798. if (this.hand === 'left') {
  73799. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  73800. }
  73801. else { // Right is the default if no hand is specified
  73802. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  73803. }
  73804. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  73805. }
  73806. else {
  73807. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  73808. path = BABYLON.GenericController.MODEL_BASE_URL;
  73809. filename = BABYLON.GenericController.MODEL_FILENAME;
  73810. }
  73811. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  73812. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  73813. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  73814. if (!_this._loadedMeshInfo) {
  73815. return;
  73816. }
  73817. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  73818. _this.attachToMesh(_this._defaultModel);
  73819. if (meshLoaded) {
  73820. meshLoaded(_this._defaultModel);
  73821. }
  73822. }, null, function (scene, message) {
  73823. BABYLON.Tools.Log(message);
  73824. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  73825. if (!forceDefault) {
  73826. _this.initControllerMesh(scene, meshLoaded, true);
  73827. }
  73828. });
  73829. };
  73830. /**
  73831. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  73832. * can be transformed by button presses and axes values, based on this._mapping.
  73833. *
  73834. * @param scene scene in which the meshes exist
  73835. * @param meshes list of meshes that make up the controller model to process
  73836. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  73837. */
  73838. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  73839. var loadedMeshInfo = null;
  73840. // Create a new mesh to contain the glTF hierarchy
  73841. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  73842. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  73843. var childMesh = null;
  73844. for (var i = 0; i < meshes.length; i++) {
  73845. var mesh = meshes[i];
  73846. if (!mesh.parent) {
  73847. // Exclude controller meshes from picking results
  73848. mesh.isPickable = false;
  73849. // Handle root node, attach to the new parentMesh
  73850. childMesh = mesh;
  73851. break;
  73852. }
  73853. }
  73854. if (childMesh) {
  73855. childMesh.setParent(parentMesh);
  73856. // Create our mesh info. Note that this method will always return non-null.
  73857. loadedMeshInfo = this.createMeshInfo(parentMesh);
  73858. }
  73859. else {
  73860. BABYLON.Tools.Warn('Could not find root node in model file.');
  73861. }
  73862. return loadedMeshInfo;
  73863. };
  73864. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  73865. var loadedMeshInfo = new LoadedMeshInfo();
  73866. var i;
  73867. loadedMeshInfo.rootNode = rootNode;
  73868. // Reset the caches
  73869. loadedMeshInfo.buttonMeshes = {};
  73870. loadedMeshInfo.axisMeshes = {};
  73871. // Button Meshes
  73872. for (i = 0; i < this._mapping.buttons.length; i++) {
  73873. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  73874. if (!buttonMeshName) {
  73875. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  73876. continue;
  73877. }
  73878. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  73879. if (!buttonMesh) {
  73880. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  73881. continue;
  73882. }
  73883. var buttonMeshInfo = {
  73884. index: i,
  73885. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  73886. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  73887. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  73888. };
  73889. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  73890. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  73891. }
  73892. else {
  73893. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  73894. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  73895. '(VALUE: ' + !!buttonMeshInfo.value +
  73896. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  73897. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  73898. ')');
  73899. }
  73900. }
  73901. // Axis Meshes
  73902. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  73903. var axisMeshName = this._mapping.axisMeshNames[i];
  73904. if (!axisMeshName) {
  73905. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  73906. continue;
  73907. }
  73908. var axisMesh = getChildByName(rootNode, axisMeshName);
  73909. if (!axisMesh) {
  73910. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  73911. continue;
  73912. }
  73913. var axisMeshInfo = {
  73914. index: i,
  73915. value: getImmediateChildByName(axisMesh, 'VALUE'),
  73916. min: getImmediateChildByName(axisMesh, 'MIN'),
  73917. max: getImmediateChildByName(axisMesh, 'MAX')
  73918. };
  73919. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  73920. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  73921. }
  73922. else {
  73923. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  73924. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  73925. '(VALUE: ' + !!axisMeshInfo.value +
  73926. ', MIN: ' + !!axisMeshInfo.min +
  73927. ', MAX:' + !!axisMeshInfo.max +
  73928. ')');
  73929. }
  73930. }
  73931. // Pointing Ray
  73932. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  73933. if (!loadedMeshInfo.pointingPoseNode) {
  73934. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  73935. }
  73936. else {
  73937. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  73938. }
  73939. return loadedMeshInfo;
  73940. // Look through all children recursively. This will return null if no mesh exists with the given name.
  73941. function getChildByName(node, name) {
  73942. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  73943. }
  73944. // Look through only immediate children. This will return null if no mesh exists with the given name.
  73945. function getImmediateChildByName(node, name) {
  73946. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  73947. }
  73948. };
  73949. /**
  73950. * Gets the ray of the controller in the direction the controller is pointing
  73951. * @param length the length the resulting ray should be
  73952. * @returns a ray in the direction the controller is pointing
  73953. */
  73954. WindowsMotionController.prototype.getForwardRay = function (length) {
  73955. if (length === void 0) { length = 100; }
  73956. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  73957. return _super.prototype.getForwardRay.call(this, length);
  73958. }
  73959. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  73960. var origin = m.getTranslation();
  73961. var forward = new BABYLON.Vector3(0, 0, -1);
  73962. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73963. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73964. return new BABYLON.Ray(origin, direction, length);
  73965. };
  73966. /**
  73967. * Disposes of the controller
  73968. */
  73969. WindowsMotionController.prototype.dispose = function () {
  73970. _super.prototype.dispose.call(this);
  73971. this.onTrackpadChangedObservable.clear();
  73972. };
  73973. /**
  73974. * The base url used to load the left and right controller models
  73975. */
  73976. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  73977. /**
  73978. * The name of the left controller model file
  73979. */
  73980. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  73981. /**
  73982. * The name of the right controller model file
  73983. */
  73984. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  73985. /**
  73986. * The controller name prefix for this controller type
  73987. */
  73988. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  73989. /**
  73990. * The controller id pattern for this controller type
  73991. */
  73992. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  73993. return WindowsMotionController;
  73994. }(BABYLON.WebVRController));
  73995. BABYLON.WindowsMotionController = WindowsMotionController;
  73996. })(BABYLON || (BABYLON = {}));
  73997. //# sourceMappingURL=babylon.windowsMotionController.js.map
  73998. var BABYLON;
  73999. (function (BABYLON) {
  74000. /**
  74001. * Gear VR Controller
  74002. */
  74003. var GearVRController = /** @class */ (function (_super) {
  74004. __extends(GearVRController, _super);
  74005. /**
  74006. * Creates a new GearVRController from a gamepad
  74007. * @param vrGamepad the gamepad that the controller should be created from
  74008. */
  74009. function GearVRController(vrGamepad) {
  74010. var _this = _super.call(this, vrGamepad) || this;
  74011. _this._maxRotationDistFromHeadset = Math.PI / 5;
  74012. _this._draggedRoomRotation = 0;
  74013. _this._tmpVector = new BABYLON.Vector3();
  74014. _this._buttonIndexToObservableNameMap = [
  74015. 'onTrackpadChangedObservable',
  74016. 'onTriggerStateChangedObservable' // Trigger
  74017. ];
  74018. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  74019. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  74020. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  74021. return _this;
  74022. }
  74023. /**
  74024. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74025. * @param poseData raw pose fromthe device
  74026. */
  74027. GearVRController.prototype.updateFromDevice = function (poseData) {
  74028. _super.prototype.updateFromDevice.call(this, poseData);
  74029. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  74030. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  74031. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  74032. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  74033. // Find the radian distance away that the headset is from the controllers rotation
  74034. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  74035. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  74036. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  74037. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  74038. this._draggedRoomRotation += rotationAmount;
  74039. // Rotate controller around headset
  74040. var sin = Math.sin(-rotationAmount);
  74041. var cos = Math.cos(-rotationAmount);
  74042. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  74043. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  74044. }
  74045. }
  74046. }
  74047. };
  74048. /**
  74049. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74050. * @param scene scene in which to add meshes
  74051. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74052. */
  74053. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74054. var _this = this;
  74055. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  74056. // Offset the controller so it will rotate around the users wrist
  74057. var mesh = new BABYLON.Mesh("", scene);
  74058. newMeshes[1].parent = mesh;
  74059. newMeshes[1].position.z = -0.15;
  74060. _this._defaultModel = mesh;
  74061. _this.attachToMesh(_this._defaultModel);
  74062. if (meshLoaded) {
  74063. meshLoaded(_this._defaultModel);
  74064. }
  74065. });
  74066. };
  74067. /**
  74068. * Called once for each button that changed state since the last frame
  74069. * @param buttonIdx Which button index changed
  74070. * @param state New state of the button
  74071. * @param changes Which properties on the state changed since last frame
  74072. */
  74073. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74074. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  74075. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  74076. // Only emit events for buttons that we know how to map from index to observable
  74077. var observable = this[observableName];
  74078. if (observable) {
  74079. observable.notifyObservers(state);
  74080. }
  74081. }
  74082. };
  74083. /**
  74084. * Base Url for the controller model.
  74085. */
  74086. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74087. /**
  74088. * File name for the controller model.
  74089. */
  74090. GearVRController.MODEL_FILENAME = 'generic.babylon';
  74091. /**
  74092. * Gamepad Id prefix used to identify this controller.
  74093. */
  74094. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  74095. return GearVRController;
  74096. }(BABYLON.WebVRController));
  74097. BABYLON.GearVRController = GearVRController;
  74098. })(BABYLON || (BABYLON = {}));
  74099. //# sourceMappingURL=babylon.gearVRController.js.map
  74100. var BABYLON;
  74101. (function (BABYLON) {
  74102. /**
  74103. * Google Daydream controller
  74104. */
  74105. var DaydreamController = /** @class */ (function (_super) {
  74106. __extends(DaydreamController, _super);
  74107. /**
  74108. * Creates a new DaydreamController from a gamepad
  74109. * @param vrGamepad the gamepad that the controller should be created from
  74110. */
  74111. function DaydreamController(vrGamepad) {
  74112. var _this = _super.call(this, vrGamepad) || this;
  74113. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  74114. return _this;
  74115. }
  74116. /**
  74117. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74118. * @param scene scene in which to add meshes
  74119. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74120. */
  74121. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74122. var _this = this;
  74123. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  74124. _this._defaultModel = newMeshes[1];
  74125. _this.attachToMesh(_this._defaultModel);
  74126. if (meshLoaded) {
  74127. meshLoaded(_this._defaultModel);
  74128. }
  74129. });
  74130. };
  74131. /**
  74132. * Called once for each button that changed state since the last frame
  74133. * @param buttonIdx Which button index changed
  74134. * @param state New state of the button
  74135. * @param changes Which properties on the state changed since last frame
  74136. */
  74137. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74138. // Daydream controller only has 1 GamepadButton (on the trackpad).
  74139. if (buttonIdx === 0) {
  74140. var observable = this.onTriggerStateChangedObservable;
  74141. if (observable) {
  74142. observable.notifyObservers(state);
  74143. }
  74144. }
  74145. else {
  74146. // If the app or home buttons are ever made available
  74147. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  74148. }
  74149. };
  74150. /**
  74151. * Base Url for the controller model.
  74152. */
  74153. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74154. /**
  74155. * File name for the controller model.
  74156. */
  74157. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  74158. /**
  74159. * Gamepad Id prefix used to identify Daydream Controller.
  74160. */
  74161. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  74162. return DaydreamController;
  74163. }(BABYLON.WebVRController));
  74164. BABYLON.DaydreamController = DaydreamController;
  74165. })(BABYLON || (BABYLON = {}));
  74166. //# sourceMappingURL=babylon.daydreamController.js.map
  74167. var BABYLON;
  74168. (function (BABYLON) {
  74169. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  74170. get: function () {
  74171. if (!this._gamepadManager) {
  74172. this._gamepadManager = new BABYLON.GamepadManager(this);
  74173. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  74174. if (!component) {
  74175. component = new GamepadSystemSceneComponent(this);
  74176. this._addComponent(component);
  74177. }
  74178. }
  74179. return this._gamepadManager;
  74180. },
  74181. enumerable: true,
  74182. configurable: true
  74183. });
  74184. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  74185. this.add(new BABYLON.FreeCameraGamepadInput());
  74186. return this;
  74187. };
  74188. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  74189. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  74190. return this;
  74191. };
  74192. /**
  74193. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  74194. */
  74195. var GamepadSystemSceneComponent = /** @class */ (function () {
  74196. /**
  74197. * Creates a new instance of the component for the given scene
  74198. * @param scene Defines the scene to register the component in
  74199. */
  74200. function GamepadSystemSceneComponent(scene) {
  74201. /**
  74202. * The component name helpfull to identify the component in the list of scene components.
  74203. */
  74204. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  74205. this.scene = scene;
  74206. }
  74207. /**
  74208. * Registers the component in a given scene
  74209. */
  74210. GamepadSystemSceneComponent.prototype.register = function () {
  74211. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  74212. };
  74213. /**
  74214. * Rebuilds the elements related to this component in case of
  74215. * context lost for instance.
  74216. */
  74217. GamepadSystemSceneComponent.prototype.rebuild = function () {
  74218. // Nothing to do for gamepads
  74219. };
  74220. /**
  74221. * Disposes the component and the associated ressources
  74222. */
  74223. GamepadSystemSceneComponent.prototype.dispose = function () {
  74224. var gamepadManager = this.scene._gamepadManager;
  74225. if (gamepadManager) {
  74226. gamepadManager.dispose();
  74227. this.scene._gamepadManager = null;
  74228. }
  74229. };
  74230. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  74231. var gamepadManager = this.scene._gamepadManager;
  74232. if (gamepadManager && gamepadManager._isMonitoring) {
  74233. gamepadManager._checkGamepadsStatus();
  74234. }
  74235. };
  74236. return GamepadSystemSceneComponent;
  74237. }());
  74238. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  74239. })(BABYLON || (BABYLON = {}));
  74240. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  74241. var BABYLON;
  74242. (function (BABYLON) {
  74243. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  74244. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  74245. });
  74246. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  74247. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  74248. });
  74249. var FollowCamera = /** @class */ (function (_super) {
  74250. __extends(FollowCamera, _super);
  74251. function FollowCamera(name, position, scene, lockedTarget) {
  74252. if (lockedTarget === void 0) { lockedTarget = null; }
  74253. var _this = _super.call(this, name, position, scene) || this;
  74254. _this.radius = 12;
  74255. _this.rotationOffset = 0;
  74256. _this.heightOffset = 4;
  74257. _this.cameraAcceleration = 0.05;
  74258. _this.maxCameraSpeed = 20;
  74259. _this.lockedTarget = lockedTarget;
  74260. return _this;
  74261. }
  74262. FollowCamera.prototype.getRadians = function (degrees) {
  74263. return degrees * Math.PI / 180;
  74264. };
  74265. FollowCamera.prototype.follow = function (cameraTarget) {
  74266. if (!cameraTarget)
  74267. return;
  74268. var yRotation;
  74269. if (cameraTarget.rotationQuaternion) {
  74270. var rotMatrix = new BABYLON.Matrix();
  74271. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  74272. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  74273. }
  74274. else {
  74275. yRotation = cameraTarget.rotation.y;
  74276. }
  74277. var radians = this.getRadians(this.rotationOffset) + yRotation;
  74278. var targetPosition = cameraTarget.getAbsolutePosition();
  74279. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  74280. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  74281. var dx = targetX - this.position.x;
  74282. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  74283. var dz = (targetZ) - this.position.z;
  74284. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  74285. var vy = dy * this.cameraAcceleration;
  74286. var vz = dz * this.cameraAcceleration * 2;
  74287. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  74288. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74289. }
  74290. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  74291. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74292. }
  74293. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  74294. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74295. }
  74296. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  74297. this.setTarget(targetPosition);
  74298. };
  74299. FollowCamera.prototype._checkInputs = function () {
  74300. _super.prototype._checkInputs.call(this);
  74301. if (this.lockedTarget) {
  74302. this.follow(this.lockedTarget);
  74303. }
  74304. };
  74305. FollowCamera.prototype.getClassName = function () {
  74306. return "FollowCamera";
  74307. };
  74308. __decorate([
  74309. BABYLON.serialize()
  74310. ], FollowCamera.prototype, "radius", void 0);
  74311. __decorate([
  74312. BABYLON.serialize()
  74313. ], FollowCamera.prototype, "rotationOffset", void 0);
  74314. __decorate([
  74315. BABYLON.serialize()
  74316. ], FollowCamera.prototype, "heightOffset", void 0);
  74317. __decorate([
  74318. BABYLON.serialize()
  74319. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  74320. __decorate([
  74321. BABYLON.serialize()
  74322. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  74323. __decorate([
  74324. BABYLON.serializeAsMeshReference("lockedTargetId")
  74325. ], FollowCamera.prototype, "lockedTarget", void 0);
  74326. return FollowCamera;
  74327. }(BABYLON.TargetCamera));
  74328. BABYLON.FollowCamera = FollowCamera;
  74329. var ArcFollowCamera = /** @class */ (function (_super) {
  74330. __extends(ArcFollowCamera, _super);
  74331. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  74332. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  74333. _this.alpha = alpha;
  74334. _this.beta = beta;
  74335. _this.radius = radius;
  74336. _this.target = target;
  74337. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  74338. _this.follow();
  74339. return _this;
  74340. }
  74341. ArcFollowCamera.prototype.follow = function () {
  74342. if (!this.target) {
  74343. return;
  74344. }
  74345. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  74346. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  74347. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  74348. var targetPosition = this.target.getAbsolutePosition();
  74349. this.position = targetPosition.add(this._cartesianCoordinates);
  74350. this.setTarget(targetPosition);
  74351. };
  74352. ArcFollowCamera.prototype._checkInputs = function () {
  74353. _super.prototype._checkInputs.call(this);
  74354. this.follow();
  74355. };
  74356. ArcFollowCamera.prototype.getClassName = function () {
  74357. return "ArcFollowCamera";
  74358. };
  74359. return ArcFollowCamera;
  74360. }(BABYLON.TargetCamera));
  74361. BABYLON.ArcFollowCamera = ArcFollowCamera;
  74362. })(BABYLON || (BABYLON = {}));
  74363. //# sourceMappingURL=babylon.followCamera.js.map
  74364. var BABYLON;
  74365. (function (BABYLON) {
  74366. // We're mainly based on the logic defined into the FreeCamera code
  74367. var UniversalCamera = /** @class */ (function (_super) {
  74368. __extends(UniversalCamera, _super);
  74369. //-- end properties for backward compatibility for inputs
  74370. function UniversalCamera(name, position, scene) {
  74371. var _this = _super.call(this, name, position, scene) || this;
  74372. _this.inputs.addGamepad();
  74373. return _this;
  74374. }
  74375. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  74376. //-- Begin properties for backward compatibility for inputs
  74377. get: function () {
  74378. var gamepad = this.inputs.attached["gamepad"];
  74379. if (gamepad)
  74380. return gamepad.gamepadAngularSensibility;
  74381. return 0;
  74382. },
  74383. set: function (value) {
  74384. var gamepad = this.inputs.attached["gamepad"];
  74385. if (gamepad)
  74386. gamepad.gamepadAngularSensibility = value;
  74387. },
  74388. enumerable: true,
  74389. configurable: true
  74390. });
  74391. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  74392. get: function () {
  74393. var gamepad = this.inputs.attached["gamepad"];
  74394. if (gamepad)
  74395. return gamepad.gamepadMoveSensibility;
  74396. return 0;
  74397. },
  74398. set: function (value) {
  74399. var gamepad = this.inputs.attached["gamepad"];
  74400. if (gamepad)
  74401. gamepad.gamepadMoveSensibility = value;
  74402. },
  74403. enumerable: true,
  74404. configurable: true
  74405. });
  74406. UniversalCamera.prototype.getClassName = function () {
  74407. return "UniversalCamera";
  74408. };
  74409. return UniversalCamera;
  74410. }(BABYLON.TouchCamera));
  74411. BABYLON.UniversalCamera = UniversalCamera;
  74412. })(BABYLON || (BABYLON = {}));
  74413. //# sourceMappingURL=babylon.universalCamera.js.map
  74414. var BABYLON;
  74415. (function (BABYLON) {
  74416. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  74417. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  74418. });
  74419. // We're mainly based on the logic defined into the FreeCamera code
  74420. var GamepadCamera = /** @class */ (function (_super) {
  74421. __extends(GamepadCamera, _super);
  74422. //-- end properties for backward compatibility for inputs
  74423. function GamepadCamera(name, position, scene) {
  74424. return _super.call(this, name, position, scene) || this;
  74425. }
  74426. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  74427. //-- Begin properties for backward compatibility for inputs
  74428. get: function () {
  74429. var gamepad = this.inputs.attached["gamepad"];
  74430. if (gamepad)
  74431. return gamepad.gamepadAngularSensibility;
  74432. return 0;
  74433. },
  74434. set: function (value) {
  74435. var gamepad = this.inputs.attached["gamepad"];
  74436. if (gamepad)
  74437. gamepad.gamepadAngularSensibility = value;
  74438. },
  74439. enumerable: true,
  74440. configurable: true
  74441. });
  74442. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  74443. get: function () {
  74444. var gamepad = this.inputs.attached["gamepad"];
  74445. if (gamepad)
  74446. return gamepad.gamepadMoveSensibility;
  74447. return 0;
  74448. },
  74449. set: function (value) {
  74450. var gamepad = this.inputs.attached["gamepad"];
  74451. if (gamepad)
  74452. gamepad.gamepadMoveSensibility = value;
  74453. },
  74454. enumerable: true,
  74455. configurable: true
  74456. });
  74457. GamepadCamera.prototype.getClassName = function () {
  74458. return "GamepadCamera";
  74459. };
  74460. return GamepadCamera;
  74461. }(BABYLON.UniversalCamera));
  74462. BABYLON.GamepadCamera = GamepadCamera;
  74463. })(BABYLON || (BABYLON = {}));
  74464. //# sourceMappingURL=babylon.gamepadCamera.js.map
  74465. var BABYLON;
  74466. (function (BABYLON) {
  74467. var PostProcessRenderPipelineManager = /** @class */ (function () {
  74468. function PostProcessRenderPipelineManager() {
  74469. this._renderPipelines = {};
  74470. }
  74471. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  74472. this._renderPipelines[renderPipeline._name] = renderPipeline;
  74473. };
  74474. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  74475. if (unique === void 0) { unique = false; }
  74476. var renderPipeline = this._renderPipelines[renderPipelineName];
  74477. if (!renderPipeline) {
  74478. return;
  74479. }
  74480. renderPipeline._attachCameras(cameras, unique);
  74481. };
  74482. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  74483. var renderPipeline = this._renderPipelines[renderPipelineName];
  74484. if (!renderPipeline) {
  74485. return;
  74486. }
  74487. renderPipeline._detachCameras(cameras);
  74488. };
  74489. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74490. var renderPipeline = this._renderPipelines[renderPipelineName];
  74491. if (!renderPipeline) {
  74492. return;
  74493. }
  74494. renderPipeline._enableEffect(renderEffectName, cameras);
  74495. };
  74496. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74497. var renderPipeline = this._renderPipelines[renderPipelineName];
  74498. if (!renderPipeline) {
  74499. return;
  74500. }
  74501. renderPipeline._disableEffect(renderEffectName, cameras);
  74502. };
  74503. PostProcessRenderPipelineManager.prototype.update = function () {
  74504. for (var renderPipelineName in this._renderPipelines) {
  74505. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74506. var pipeline = this._renderPipelines[renderPipelineName];
  74507. if (!pipeline.isSupported) {
  74508. pipeline.dispose();
  74509. delete this._renderPipelines[renderPipelineName];
  74510. }
  74511. else {
  74512. pipeline._update();
  74513. }
  74514. }
  74515. }
  74516. };
  74517. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  74518. for (var renderPipelineName in this._renderPipelines) {
  74519. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74520. var pipeline = this._renderPipelines[renderPipelineName];
  74521. pipeline._rebuild();
  74522. }
  74523. }
  74524. };
  74525. PostProcessRenderPipelineManager.prototype.dispose = function () {
  74526. for (var renderPipelineName in this._renderPipelines) {
  74527. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74528. var pipeline = this._renderPipelines[renderPipelineName];
  74529. pipeline.dispose();
  74530. }
  74531. }
  74532. };
  74533. return PostProcessRenderPipelineManager;
  74534. }());
  74535. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  74536. })(BABYLON || (BABYLON = {}));
  74537. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  74538. var BABYLON;
  74539. (function (BABYLON) {
  74540. /**
  74541. * This represents a set of one or more post processes in Babylon.
  74542. * A post process can be used to apply a shader to a texture after it is rendered.
  74543. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  74544. */
  74545. var PostProcessRenderEffect = /** @class */ (function () {
  74546. /**
  74547. * Instantiates a post process render effect.
  74548. * A post process can be used to apply a shader to a texture after it is rendered.
  74549. * @param engine The engine the effect is tied to
  74550. * @param name The name of the effect
  74551. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  74552. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  74553. */
  74554. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  74555. this._name = name;
  74556. this._singleInstance = singleInstance || true;
  74557. this._getPostProcesses = getPostProcesses;
  74558. this._cameras = {};
  74559. this._indicesForCamera = {};
  74560. this._postProcesses = {};
  74561. }
  74562. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  74563. /**
  74564. * Checks if all the post processes in the effect are supported.
  74565. */
  74566. get: function () {
  74567. for (var index in this._postProcesses) {
  74568. if (this._postProcesses.hasOwnProperty(index)) {
  74569. var pps = this._postProcesses[index];
  74570. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  74571. if (!pps[ppIndex].isSupported) {
  74572. return false;
  74573. }
  74574. }
  74575. }
  74576. }
  74577. return true;
  74578. },
  74579. enumerable: true,
  74580. configurable: true
  74581. });
  74582. /**
  74583. * Updates the current state of the effect
  74584. */
  74585. PostProcessRenderEffect.prototype._update = function () {
  74586. };
  74587. /**
  74588. * Attaches the effect on cameras
  74589. * @param cameras The camera to attach to.
  74590. */
  74591. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  74592. var _this = this;
  74593. var cameraKey;
  74594. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74595. if (!cams) {
  74596. return;
  74597. }
  74598. for (var i = 0; i < cams.length; i++) {
  74599. var camera = cams[i];
  74600. var cameraName = camera.name;
  74601. if (this._singleInstance) {
  74602. cameraKey = 0;
  74603. }
  74604. else {
  74605. cameraKey = cameraName;
  74606. }
  74607. if (!this._postProcesses[cameraKey]) {
  74608. var postProcess = this._getPostProcesses();
  74609. if (postProcess) {
  74610. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  74611. }
  74612. }
  74613. if (!this._indicesForCamera[cameraName]) {
  74614. this._indicesForCamera[cameraName] = [];
  74615. }
  74616. this._postProcesses[cameraKey].forEach(function (postProcess) {
  74617. var index = camera.attachPostProcess(postProcess);
  74618. _this._indicesForCamera[cameraName].push(index);
  74619. });
  74620. if (!this._cameras[cameraName]) {
  74621. this._cameras[cameraName] = camera;
  74622. }
  74623. }
  74624. };
  74625. /**
  74626. * Detatches the effect on cameras
  74627. * @param cameras The camera to detatch from.
  74628. */
  74629. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  74630. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74631. if (!cams) {
  74632. return;
  74633. }
  74634. for (var i = 0; i < cams.length; i++) {
  74635. var camera = cams[i];
  74636. var cameraName = camera.name;
  74637. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74638. camera.detachPostProcess(postProcess);
  74639. });
  74640. if (this._cameras[cameraName]) {
  74641. //this._indicesForCamera.splice(index, 1);
  74642. this._cameras[cameraName] = null;
  74643. }
  74644. }
  74645. };
  74646. /**
  74647. * Enables the effect on given cameras
  74648. * @param cameras The camera to enable.
  74649. */
  74650. PostProcessRenderEffect.prototype._enable = function (cameras) {
  74651. var _this = this;
  74652. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74653. if (!cams) {
  74654. return;
  74655. }
  74656. for (var i = 0; i < cams.length; i++) {
  74657. var camera = cams[i];
  74658. var cameraName = camera.name;
  74659. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  74660. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  74661. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74662. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  74663. });
  74664. }
  74665. }
  74666. }
  74667. };
  74668. /**
  74669. * Disables the effect on the given cameras
  74670. * @param cameras The camera to disable.
  74671. */
  74672. PostProcessRenderEffect.prototype._disable = function (cameras) {
  74673. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74674. if (!cams) {
  74675. return;
  74676. }
  74677. for (var i = 0; i < cams.length; i++) {
  74678. var camera = cams[i];
  74679. var cameraName = camera.name;
  74680. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74681. camera.detachPostProcess(postProcess);
  74682. });
  74683. }
  74684. };
  74685. /**
  74686. * Gets a list of the post processes contained in the effect.
  74687. * @param camera The camera to get the post processes on.
  74688. * @returns The list of the post processes in the effect.
  74689. */
  74690. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  74691. if (this._singleInstance) {
  74692. return this._postProcesses[0];
  74693. }
  74694. else {
  74695. if (!camera) {
  74696. return null;
  74697. }
  74698. return this._postProcesses[camera.name];
  74699. }
  74700. };
  74701. return PostProcessRenderEffect;
  74702. }());
  74703. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  74704. })(BABYLON || (BABYLON = {}));
  74705. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  74706. var BABYLON;
  74707. (function (BABYLON) {
  74708. var PostProcessRenderPipeline = /** @class */ (function () {
  74709. function PostProcessRenderPipeline(engine, name) {
  74710. this.engine = engine;
  74711. this._name = name;
  74712. this._renderEffects = {};
  74713. this._renderEffectsForIsolatedPass = new Array();
  74714. this._cameras = [];
  74715. }
  74716. PostProcessRenderPipeline.prototype.getClassName = function () {
  74717. return "PostProcessRenderPipeline";
  74718. };
  74719. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  74720. get: function () {
  74721. for (var renderEffectName in this._renderEffects) {
  74722. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74723. if (!this._renderEffects[renderEffectName].isSupported) {
  74724. return false;
  74725. }
  74726. }
  74727. }
  74728. return true;
  74729. },
  74730. enumerable: true,
  74731. configurable: true
  74732. });
  74733. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  74734. this._renderEffects[renderEffect._name] = renderEffect;
  74735. };
  74736. // private
  74737. PostProcessRenderPipeline.prototype._rebuild = function () {
  74738. };
  74739. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  74740. var renderEffects = this._renderEffects[renderEffectName];
  74741. if (!renderEffects) {
  74742. return;
  74743. }
  74744. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74745. };
  74746. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  74747. var renderEffects = this._renderEffects[renderEffectName];
  74748. if (!renderEffects) {
  74749. return;
  74750. }
  74751. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74752. };
  74753. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  74754. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74755. if (!cams) {
  74756. return;
  74757. }
  74758. var indicesToDelete = [];
  74759. var i;
  74760. for (i = 0; i < cams.length; i++) {
  74761. var camera = cams[i];
  74762. var cameraName = camera.name;
  74763. if (this._cameras.indexOf(camera) === -1) {
  74764. this._cameras[cameraName] = camera;
  74765. }
  74766. else if (unique) {
  74767. indicesToDelete.push(i);
  74768. }
  74769. }
  74770. for (i = 0; i < indicesToDelete.length; i++) {
  74771. cameras.splice(indicesToDelete[i], 1);
  74772. }
  74773. for (var renderEffectName in this._renderEffects) {
  74774. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74775. this._renderEffects[renderEffectName]._attachCameras(cams);
  74776. }
  74777. }
  74778. };
  74779. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  74780. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74781. if (!cams) {
  74782. return;
  74783. }
  74784. for (var renderEffectName in this._renderEffects) {
  74785. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74786. this._renderEffects[renderEffectName]._detachCameras(cams);
  74787. }
  74788. }
  74789. for (var i = 0; i < cams.length; i++) {
  74790. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  74791. }
  74792. };
  74793. PostProcessRenderPipeline.prototype._update = function () {
  74794. for (var renderEffectName in this._renderEffects) {
  74795. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74796. this._renderEffects[renderEffectName]._update();
  74797. }
  74798. }
  74799. for (var i = 0; i < this._cameras.length; i++) {
  74800. var cameraName = this._cameras[i].name;
  74801. if (this._renderEffectsForIsolatedPass[cameraName]) {
  74802. this._renderEffectsForIsolatedPass[cameraName]._update();
  74803. }
  74804. }
  74805. };
  74806. PostProcessRenderPipeline.prototype._reset = function () {
  74807. this._renderEffects = {};
  74808. this._renderEffectsForIsolatedPass = new Array();
  74809. };
  74810. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  74811. // 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)
  74812. var effectKeys = Object.keys(this._renderEffects);
  74813. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  74814. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  74815. if (postProcesses) {
  74816. postProcesses[0].samples = sampleCount;
  74817. return true;
  74818. }
  74819. }
  74820. return false;
  74821. };
  74822. PostProcessRenderPipeline.prototype.dispose = function () {
  74823. // Must be implemented by children
  74824. };
  74825. __decorate([
  74826. BABYLON.serialize()
  74827. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  74828. return PostProcessRenderPipeline;
  74829. }());
  74830. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  74831. })(BABYLON || (BABYLON = {}));
  74832. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  74833. var BABYLON;
  74834. (function (BABYLON) {
  74835. /**
  74836. * This represents a depth renderer in Babylon.
  74837. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  74838. */
  74839. var DepthRenderer = /** @class */ (function () {
  74840. /**
  74841. * Instantiates a depth renderer
  74842. * @param scene The scene the renderer belongs to
  74843. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  74844. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  74845. */
  74846. function DepthRenderer(scene, type, camera) {
  74847. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  74848. if (camera === void 0) { camera = null; }
  74849. var _this = this;
  74850. this._scene = scene;
  74851. this._camera = camera;
  74852. var engine = scene.getEngine();
  74853. // Render target
  74854. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  74855. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74856. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74857. this._depthMap.refreshRate = 1;
  74858. this._depthMap.renderParticles = false;
  74859. this._depthMap.renderList = null;
  74860. // Camera to get depth map from to support multiple concurrent cameras
  74861. this._depthMap.activeCamera = this._camera;
  74862. this._depthMap.ignoreCameraViewport = true;
  74863. this._depthMap.useCameraPostProcesses = false;
  74864. // set default depth value to 1.0 (far away)
  74865. this._depthMap.onClearObservable.add(function (engine) {
  74866. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  74867. });
  74868. // Custom render function
  74869. var renderSubMesh = function (subMesh) {
  74870. var mesh = subMesh.getRenderingMesh();
  74871. var scene = _this._scene;
  74872. var engine = scene.getEngine();
  74873. var material = subMesh.getMaterial();
  74874. if (!material) {
  74875. return;
  74876. }
  74877. // Culling and reverse (right handed system)
  74878. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  74879. // Managing instances
  74880. var batch = mesh._getInstancesRenderList(subMesh._id);
  74881. if (batch.mustReturn) {
  74882. return;
  74883. }
  74884. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74885. var camera = _this._camera || scene.activeCamera;
  74886. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  74887. engine.enableEffect(_this._effect);
  74888. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  74889. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74890. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  74891. // Alpha test
  74892. if (material && material.needAlphaTesting()) {
  74893. var alphaTexture = material.getAlphaTestTexture();
  74894. if (alphaTexture) {
  74895. _this._effect.setTexture("diffuseSampler", alphaTexture);
  74896. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74897. }
  74898. }
  74899. // Bones
  74900. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74901. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74902. }
  74903. // Draw
  74904. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74905. }
  74906. };
  74907. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74908. var index;
  74909. if (depthOnlySubMeshes.length) {
  74910. engine.setColorWrite(false);
  74911. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74912. renderSubMesh(depthOnlySubMeshes.data[index]);
  74913. }
  74914. engine.setColorWrite(true);
  74915. }
  74916. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74917. renderSubMesh(opaqueSubMeshes.data[index]);
  74918. }
  74919. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74920. renderSubMesh(alphaTestSubMeshes.data[index]);
  74921. }
  74922. };
  74923. }
  74924. /**
  74925. * Creates the depth rendering effect and checks if the effect is ready.
  74926. * @param subMesh The submesh to be used to render the depth map of
  74927. * @param useInstances If multiple world instances should be used
  74928. * @returns if the depth renderer is ready to render the depth map
  74929. */
  74930. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  74931. var material = subMesh.getMaterial();
  74932. if (material.disableDepthWrite) {
  74933. return false;
  74934. }
  74935. var defines = [];
  74936. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74937. var mesh = subMesh.getMesh();
  74938. // Alpha test
  74939. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  74940. defines.push("#define ALPHATEST");
  74941. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74942. attribs.push(BABYLON.VertexBuffer.UVKind);
  74943. defines.push("#define UV1");
  74944. }
  74945. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74946. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74947. defines.push("#define UV2");
  74948. }
  74949. }
  74950. // Bones
  74951. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74952. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74953. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74954. if (mesh.numBoneInfluencers > 4) {
  74955. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74956. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74957. }
  74958. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74959. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74960. }
  74961. else {
  74962. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74963. }
  74964. // Instances
  74965. if (useInstances) {
  74966. defines.push("#define INSTANCES");
  74967. attribs.push("world0");
  74968. attribs.push("world1");
  74969. attribs.push("world2");
  74970. attribs.push("world3");
  74971. }
  74972. // Get correct effect
  74973. var join = defines.join("\n");
  74974. if (this._cachedDefines !== join) {
  74975. this._cachedDefines = join;
  74976. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  74977. }
  74978. return this._effect.isReady();
  74979. };
  74980. /**
  74981. * Gets the texture which the depth map will be written to.
  74982. * @returns The depth map texture
  74983. */
  74984. DepthRenderer.prototype.getDepthMap = function () {
  74985. return this._depthMap;
  74986. };
  74987. /**
  74988. * Disposes of the depth renderer.
  74989. */
  74990. DepthRenderer.prototype.dispose = function () {
  74991. this._depthMap.dispose();
  74992. };
  74993. return DepthRenderer;
  74994. }());
  74995. BABYLON.DepthRenderer = DepthRenderer;
  74996. })(BABYLON || (BABYLON = {}));
  74997. //# sourceMappingURL=babylon.depthRenderer.js.map
  74998. var BABYLON;
  74999. (function (BABYLON) {
  75000. var SSAORenderingPipeline = /** @class */ (function (_super) {
  75001. __extends(SSAORenderingPipeline, _super);
  75002. /**
  75003. * @constructor
  75004. * @param {string} name - The rendering pipeline name
  75005. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75006. * @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 }
  75007. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75008. */
  75009. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  75010. var _this = _super.call(this, scene.getEngine(), name) || this;
  75011. // Members
  75012. /**
  75013. * The PassPostProcess id in the pipeline that contains the original scene color
  75014. */
  75015. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75016. /**
  75017. * The SSAO PostProcess id in the pipeline
  75018. */
  75019. _this.SSAORenderEffect = "SSAORenderEffect";
  75020. /**
  75021. * The horizontal blur PostProcess id in the pipeline
  75022. */
  75023. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75024. /**
  75025. * The vertical blur PostProcess id in the pipeline
  75026. */
  75027. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75028. /**
  75029. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75030. */
  75031. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75032. /**
  75033. * The output strength of the SSAO post-process. Default value is 1.0.
  75034. */
  75035. _this.totalStrength = 1.0;
  75036. /**
  75037. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  75038. */
  75039. _this.radius = 0.0001;
  75040. /**
  75041. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  75042. * Must not be equal to fallOff and superior to fallOff.
  75043. * Default value is 0.975
  75044. */
  75045. _this.area = 0.0075;
  75046. /**
  75047. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  75048. * Must not be equal to area and inferior to area.
  75049. * Default value is 0.0
  75050. */
  75051. _this.fallOff = 0.000001;
  75052. /**
  75053. * The base color of the SSAO post-process
  75054. * The final result is "base + ssao" between [0, 1]
  75055. */
  75056. _this.base = 0.5;
  75057. _this._firstUpdate = true;
  75058. _this._scene = scene;
  75059. // Set up assets
  75060. _this._createRandomTexture();
  75061. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75062. var ssaoRatio = ratio.ssaoRatio || ratio;
  75063. var combineRatio = ratio.combineRatio || ratio;
  75064. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75065. _this._createSSAOPostProcess(ssaoRatio);
  75066. _this._createBlurPostProcess(ssaoRatio);
  75067. _this._createSSAOCombinePostProcess(combineRatio);
  75068. // Set up pipeline
  75069. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75070. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75071. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75072. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75073. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75074. // Finish
  75075. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75076. if (cameras)
  75077. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75078. return _this;
  75079. }
  75080. // Public Methods
  75081. /**
  75082. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75083. */
  75084. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75085. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75086. for (var i = 0; i < this._scene.cameras.length; i++) {
  75087. var camera = this._scene.cameras[i];
  75088. this._originalColorPostProcess.dispose(camera);
  75089. this._ssaoPostProcess.dispose(camera);
  75090. this._blurHPostProcess.dispose(camera);
  75091. this._blurVPostProcess.dispose(camera);
  75092. this._ssaoCombinePostProcess.dispose(camera);
  75093. }
  75094. this._randomTexture.dispose();
  75095. if (disableDepthRender)
  75096. this._scene.disableDepthRenderer();
  75097. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75098. _super.prototype.dispose.call(this);
  75099. };
  75100. // Private Methods
  75101. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  75102. var _this = this;
  75103. var size = 16;
  75104. 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);
  75105. 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);
  75106. this._blurHPostProcess.onActivateObservable.add(function () {
  75107. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  75108. _this._blurHPostProcess.kernel = size * dw;
  75109. });
  75110. this._blurVPostProcess.onActivateObservable.add(function () {
  75111. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  75112. _this._blurVPostProcess.kernel = size * dw;
  75113. });
  75114. };
  75115. SSAORenderingPipeline.prototype._rebuild = function () {
  75116. this._firstUpdate = true;
  75117. _super.prototype._rebuild.call(this);
  75118. };
  75119. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75120. var _this = this;
  75121. var numSamples = 16;
  75122. var sampleSphere = [
  75123. 0.5381, 0.1856, -0.4319,
  75124. 0.1379, 0.2486, 0.4430,
  75125. 0.3371, 0.5679, -0.0057,
  75126. -0.6999, -0.0451, -0.0019,
  75127. 0.0689, -0.1598, -0.8547,
  75128. 0.0560, 0.0069, -0.1843,
  75129. -0.0146, 0.1402, 0.0762,
  75130. 0.0100, -0.1924, -0.0344,
  75131. -0.3577, -0.5301, -0.4358,
  75132. -0.3169, 0.1063, 0.0158,
  75133. 0.0103, -0.5869, 0.0046,
  75134. -0.0897, -0.4940, 0.3287,
  75135. 0.7119, -0.0154, -0.0918,
  75136. -0.0533, 0.0596, -0.5411,
  75137. 0.0352, -0.0631, 0.5460,
  75138. -0.4776, 0.2847, -0.0271
  75139. ];
  75140. var samplesFactor = 1.0 / numSamples;
  75141. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  75142. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75143. "area", "fallOff", "base", "range", "viewport"
  75144. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75145. this._ssaoPostProcess.onApply = function (effect) {
  75146. if (_this._firstUpdate) {
  75147. effect.setArray3("sampleSphere", sampleSphere);
  75148. effect.setFloat("samplesFactor", samplesFactor);
  75149. effect.setFloat("randTextureTiles", 4.0);
  75150. }
  75151. effect.setFloat("totalStrength", _this.totalStrength);
  75152. effect.setFloat("radius", _this.radius);
  75153. effect.setFloat("area", _this.area);
  75154. effect.setFloat("fallOff", _this.fallOff);
  75155. effect.setFloat("base", _this.base);
  75156. effect.setTexture("textureSampler", _this._depthTexture);
  75157. effect.setTexture("randomSampler", _this._randomTexture);
  75158. };
  75159. };
  75160. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75161. var _this = this;
  75162. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75163. this._ssaoCombinePostProcess.onApply = function (effect) {
  75164. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  75165. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75166. };
  75167. };
  75168. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  75169. var size = 512;
  75170. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75171. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75172. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75173. var context = this._randomTexture.getContext();
  75174. var rand = function (min, max) {
  75175. return Math.random() * (max - min) + min;
  75176. };
  75177. var randVector = BABYLON.Vector3.Zero();
  75178. for (var x = 0; x < size; x++) {
  75179. for (var y = 0; y < size; y++) {
  75180. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  75181. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  75182. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  75183. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75184. context.fillRect(x, y, 1, 1);
  75185. }
  75186. }
  75187. this._randomTexture.update(false);
  75188. };
  75189. __decorate([
  75190. BABYLON.serialize()
  75191. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  75192. __decorate([
  75193. BABYLON.serialize()
  75194. ], SSAORenderingPipeline.prototype, "radius", void 0);
  75195. __decorate([
  75196. BABYLON.serialize()
  75197. ], SSAORenderingPipeline.prototype, "area", void 0);
  75198. __decorate([
  75199. BABYLON.serialize()
  75200. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  75201. __decorate([
  75202. BABYLON.serialize()
  75203. ], SSAORenderingPipeline.prototype, "base", void 0);
  75204. return SSAORenderingPipeline;
  75205. }(BABYLON.PostProcessRenderPipeline));
  75206. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  75207. })(BABYLON || (BABYLON = {}));
  75208. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  75209. var BABYLON;
  75210. (function (BABYLON) {
  75211. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  75212. __extends(SSAO2RenderingPipeline, _super);
  75213. /**
  75214. * @constructor
  75215. * @param {string} name - The rendering pipeline name
  75216. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75217. * @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 }
  75218. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75219. */
  75220. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  75221. var _this = _super.call(this, scene.getEngine(), name) || this;
  75222. // Members
  75223. /**
  75224. * The PassPostProcess id in the pipeline that contains the original scene color
  75225. */
  75226. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75227. /**
  75228. * The SSAO PostProcess id in the pipeline
  75229. */
  75230. _this.SSAORenderEffect = "SSAORenderEffect";
  75231. /**
  75232. * The horizontal blur PostProcess id in the pipeline
  75233. */
  75234. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75235. /**
  75236. * The vertical blur PostProcess id in the pipeline
  75237. */
  75238. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75239. /**
  75240. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75241. */
  75242. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75243. /**
  75244. * The output strength of the SSAO post-process. Default value is 1.0.
  75245. */
  75246. _this.totalStrength = 1.0;
  75247. /**
  75248. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  75249. */
  75250. _this.maxZ = 100.0;
  75251. /**
  75252. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  75253. */
  75254. _this.minZAspect = 0.2;
  75255. /**
  75256. * Number of samples used for the SSAO calculations. Default value is 8
  75257. */
  75258. _this._samples = 8;
  75259. /**
  75260. * Are we using bilateral blur ?
  75261. */
  75262. _this._expensiveBlur = true;
  75263. /**
  75264. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  75265. */
  75266. _this.radius = 2.0;
  75267. /**
  75268. * The base color of the SSAO post-process
  75269. * The final result is "base + ssao" between [0, 1]
  75270. */
  75271. _this.base = 0.1;
  75272. _this._firstUpdate = true;
  75273. _this._scene = scene;
  75274. _this._ratio = ratio;
  75275. if (!_this.isSupported) {
  75276. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  75277. return _this;
  75278. }
  75279. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  75280. var blurRatio = _this._ratio.blurRatio || ratio;
  75281. // Set up assets
  75282. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  75283. _this._createRandomTexture();
  75284. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  75285. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  75286. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75287. _this._createSSAOPostProcess(1.0);
  75288. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  75289. _this._createSSAOCombinePostProcess(blurRatio);
  75290. // Set up pipeline
  75291. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75292. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75293. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75294. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75295. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75296. // Finish
  75297. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75298. if (cameras)
  75299. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75300. return _this;
  75301. }
  75302. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  75303. get: function () {
  75304. return this._samples;
  75305. },
  75306. set: function (n) {
  75307. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  75308. this._samples = n;
  75309. this._sampleSphere = this._generateHemisphere();
  75310. this._firstUpdate = true;
  75311. },
  75312. enumerable: true,
  75313. configurable: true
  75314. });
  75315. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  75316. get: function () {
  75317. return this._expensiveBlur;
  75318. },
  75319. set: function (b) {
  75320. 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"]);
  75321. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  75322. this._expensiveBlur = b;
  75323. this._firstUpdate = true;
  75324. },
  75325. enumerable: true,
  75326. configurable: true
  75327. });
  75328. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  75329. /**
  75330. * Support test.
  75331. */
  75332. get: function () {
  75333. var engine = BABYLON.Engine.LastCreatedEngine;
  75334. if (!engine) {
  75335. return false;
  75336. }
  75337. return engine.getCaps().drawBuffersExtension;
  75338. },
  75339. enumerable: true,
  75340. configurable: true
  75341. });
  75342. // Public Methods
  75343. /**
  75344. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75345. */
  75346. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  75347. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  75348. for (var i = 0; i < this._scene.cameras.length; i++) {
  75349. var camera = this._scene.cameras[i];
  75350. this._originalColorPostProcess.dispose(camera);
  75351. this._ssaoPostProcess.dispose(camera);
  75352. this._blurHPostProcess.dispose(camera);
  75353. this._blurVPostProcess.dispose(camera);
  75354. this._ssaoCombinePostProcess.dispose(camera);
  75355. }
  75356. this._randomTexture.dispose();
  75357. if (disableGeometryBufferRenderer)
  75358. this._scene.disableGeometryBufferRenderer();
  75359. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75360. _super.prototype.dispose.call(this);
  75361. };
  75362. // Private Methods
  75363. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  75364. var _this = this;
  75365. this._samplerOffsets = [];
  75366. var expensive = this.expensiveBlur;
  75367. for (var i = -8; i < 8; i++) {
  75368. this._samplerOffsets.push(i * 2 + 0.5);
  75369. }
  75370. 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");
  75371. this._blurHPostProcess.onApply = function (effect) {
  75372. if (!_this._scene.activeCamera) {
  75373. return;
  75374. }
  75375. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  75376. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75377. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75378. effect.setFloat("radius", _this.radius);
  75379. effect.setTexture("depthSampler", _this._depthTexture);
  75380. if (_this._firstUpdate) {
  75381. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75382. }
  75383. };
  75384. 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");
  75385. this._blurVPostProcess.onApply = function (effect) {
  75386. if (!_this._scene.activeCamera) {
  75387. return;
  75388. }
  75389. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  75390. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75391. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75392. effect.setFloat("radius", _this.radius);
  75393. effect.setTexture("depthSampler", _this._depthTexture);
  75394. if (_this._firstUpdate) {
  75395. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75396. _this._firstUpdate = false;
  75397. }
  75398. };
  75399. };
  75400. SSAO2RenderingPipeline.prototype._rebuild = function () {
  75401. this._firstUpdate = true;
  75402. _super.prototype._rebuild.call(this);
  75403. };
  75404. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  75405. var numSamples = this.samples;
  75406. var result = [];
  75407. var vector, scale;
  75408. var rand = function (min, max) {
  75409. return Math.random() * (max - min) + min;
  75410. };
  75411. var i = 0;
  75412. while (i < numSamples) {
  75413. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  75414. vector.normalize();
  75415. scale = i / numSamples;
  75416. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  75417. vector.scaleInPlace(scale);
  75418. result.push(vector.x, vector.y, vector.z);
  75419. i++;
  75420. }
  75421. return result;
  75422. };
  75423. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75424. var _this = this;
  75425. var numSamples = this.samples;
  75426. this._sampleSphere = this._generateHemisphere();
  75427. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  75428. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75429. "base", "range", "projection", "near", "far", "texelSize",
  75430. "xViewport", "yViewport", "maxZ", "minZAspect"
  75431. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75432. this._ssaoPostProcess.onApply = function (effect) {
  75433. if (_this._firstUpdate) {
  75434. effect.setArray3("sampleSphere", _this._sampleSphere);
  75435. effect.setFloat("randTextureTiles", 4.0);
  75436. }
  75437. if (!_this._scene.activeCamera) {
  75438. return;
  75439. }
  75440. effect.setFloat("samplesFactor", 1 / _this.samples);
  75441. effect.setFloat("totalStrength", _this.totalStrength);
  75442. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  75443. effect.setFloat("radius", _this.radius);
  75444. effect.setFloat("maxZ", _this.maxZ);
  75445. effect.setFloat("minZAspect", _this.minZAspect);
  75446. effect.setFloat("base", _this.base);
  75447. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75448. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75449. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  75450. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  75451. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  75452. effect.setTexture("textureSampler", _this._depthTexture);
  75453. effect.setTexture("normalSampler", _this._normalTexture);
  75454. effect.setTexture("randomSampler", _this._randomTexture);
  75455. };
  75456. };
  75457. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75458. var _this = this;
  75459. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75460. this._ssaoCombinePostProcess.onApply = function (effect) {
  75461. var viewport = _this._scene.activeCamera.viewport;
  75462. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  75463. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75464. };
  75465. };
  75466. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  75467. var size = 512;
  75468. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75469. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75470. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75471. var context = this._randomTexture.getContext();
  75472. var rand = function (min, max) {
  75473. return Math.random() * (max - min) + min;
  75474. };
  75475. var randVector = BABYLON.Vector3.Zero();
  75476. for (var x = 0; x < size; x++) {
  75477. for (var y = 0; y < size; y++) {
  75478. randVector.x = rand(0.0, 1.0);
  75479. randVector.y = rand(0.0, 1.0);
  75480. randVector.z = 0.0;
  75481. randVector.normalize();
  75482. randVector.scaleInPlace(255);
  75483. randVector.x = Math.floor(randVector.x);
  75484. randVector.y = Math.floor(randVector.y);
  75485. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75486. context.fillRect(x, y, 1, 1);
  75487. }
  75488. }
  75489. this._randomTexture.update(false);
  75490. };
  75491. /**
  75492. * Serialize the rendering pipeline (Used when exporting)
  75493. * @returns the serialized object
  75494. */
  75495. SSAO2RenderingPipeline.prototype.serialize = function () {
  75496. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75497. serializationObject.customType = "SSAO2RenderingPipeline";
  75498. return serializationObject;
  75499. };
  75500. /**
  75501. * Parse the serialized pipeline
  75502. * @param source Source pipeline.
  75503. * @param scene The scene to load the pipeline to.
  75504. * @param rootUrl The URL of the serialized pipeline.
  75505. * @returns An instantiated pipeline from the serialized object.
  75506. */
  75507. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  75508. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75509. };
  75510. __decorate([
  75511. BABYLON.serialize()
  75512. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  75513. __decorate([
  75514. BABYLON.serialize()
  75515. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  75516. __decorate([
  75517. BABYLON.serialize()
  75518. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  75519. __decorate([
  75520. BABYLON.serialize("samples")
  75521. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  75522. __decorate([
  75523. BABYLON.serialize()
  75524. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  75525. __decorate([
  75526. BABYLON.serialize("expensiveBlur")
  75527. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  75528. __decorate([
  75529. BABYLON.serialize()
  75530. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  75531. __decorate([
  75532. BABYLON.serialize()
  75533. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  75534. return SSAO2RenderingPipeline;
  75535. }(BABYLON.PostProcessRenderPipeline));
  75536. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  75537. })(BABYLON || (BABYLON = {}));
  75538. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  75539. // BABYLON.JS Chromatic Aberration GLSL Shader
  75540. // Author: Olivier Guyot
  75541. // Separates very slightly R, G and B colors on the edges of the screen
  75542. // Inspired by Francois Tarlier & Martins Upitis
  75543. var BABYLON;
  75544. (function (BABYLON) {
  75545. var LensRenderingPipeline = /** @class */ (function (_super) {
  75546. __extends(LensRenderingPipeline, _super);
  75547. /**
  75548. * @constructor
  75549. *
  75550. * Effect parameters are as follow:
  75551. * {
  75552. * chromatic_aberration: number; // from 0 to x (1 for realism)
  75553. * edge_blur: number; // from 0 to x (1 for realism)
  75554. * distortion: number; // from 0 to x (1 for realism)
  75555. * grain_amount: number; // from 0 to 1
  75556. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  75557. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  75558. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  75559. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  75560. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  75561. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  75562. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  75563. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  75564. * }
  75565. * Note: if an effect parameter is unset, effect is disabled
  75566. *
  75567. * @param {string} name - The rendering pipeline name
  75568. * @param {object} parameters - An object containing all parameters (see above)
  75569. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75570. * @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)
  75571. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75572. */
  75573. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  75574. if (ratio === void 0) { ratio = 1.0; }
  75575. var _this = _super.call(this, scene.getEngine(), name) || this;
  75576. // Lens effects can be of the following:
  75577. // - chromatic aberration (slight shift of RGB colors)
  75578. // - blur on the edge of the lens
  75579. // - lens distortion
  75580. // - depth-of-field blur & highlights enhancing
  75581. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  75582. // - grain effect (noise or custom texture)
  75583. // Two additional texture samplers are needed:
  75584. // - depth map (for depth-of-field)
  75585. // - grain texture
  75586. /**
  75587. * The chromatic aberration PostProcess id in the pipeline
  75588. */
  75589. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  75590. /**
  75591. * The highlights enhancing PostProcess id in the pipeline
  75592. */
  75593. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  75594. /**
  75595. * The depth-of-field PostProcess id in the pipeline
  75596. */
  75597. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  75598. _this._scene = scene;
  75599. // Fetch texture samplers
  75600. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75601. if (parameters.grain_texture) {
  75602. _this._grainTexture = parameters.grain_texture;
  75603. }
  75604. else {
  75605. _this._createGrainTexture();
  75606. }
  75607. // save parameters
  75608. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  75609. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  75610. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  75611. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  75612. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  75613. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  75614. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  75615. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  75616. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  75617. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  75618. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  75619. // Create effects
  75620. _this._createChromaticAberrationPostProcess(ratio);
  75621. _this._createHighlightsPostProcess(ratio);
  75622. _this._createDepthOfFieldPostProcess(ratio / 4);
  75623. // Set up pipeline
  75624. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  75625. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  75626. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  75627. if (_this._highlightsGain === -1) {
  75628. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  75629. }
  75630. // Finish
  75631. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75632. if (cameras) {
  75633. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75634. }
  75635. return _this;
  75636. }
  75637. // public methods (self explanatory)
  75638. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  75639. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  75640. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  75641. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  75642. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  75643. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  75644. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  75645. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  75646. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  75647. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  75648. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  75649. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  75650. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  75651. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  75652. };
  75653. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  75654. this._highlightsPostProcess.updateEffect();
  75655. };
  75656. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  75657. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  75658. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  75659. this._highlightsGain = amount;
  75660. };
  75661. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  75662. if (this._highlightsGain === -1) {
  75663. this._highlightsGain = 1.0;
  75664. }
  75665. this._highlightsThreshold = amount;
  75666. };
  75667. LensRenderingPipeline.prototype.disableHighlights = function () {
  75668. this._highlightsGain = -1;
  75669. };
  75670. /**
  75671. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  75672. */
  75673. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75674. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75675. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75676. this._chromaticAberrationPostProcess = null;
  75677. this._highlightsPostProcess = null;
  75678. this._depthOfFieldPostProcess = null;
  75679. this._grainTexture.dispose();
  75680. if (disableDepthRender)
  75681. this._scene.disableDepthRenderer();
  75682. };
  75683. // colors shifting and distortion
  75684. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  75685. var _this = this;
  75686. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  75687. [], // samplers
  75688. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75689. this._chromaticAberrationPostProcess.onApply = function (effect) {
  75690. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  75691. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75692. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75693. effect.setFloat('radialIntensity', 1);
  75694. effect.setFloat2('direction', 17, 17);
  75695. effect.setFloat2('centerPosition', 0.5, 0.5);
  75696. };
  75697. };
  75698. // highlights enhancing
  75699. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  75700. var _this = this;
  75701. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  75702. [], // samplers
  75703. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  75704. this._highlightsPostProcess.onApply = function (effect) {
  75705. effect.setFloat('gain', _this._highlightsGain);
  75706. effect.setFloat('threshold', _this._highlightsThreshold);
  75707. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  75708. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75709. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75710. };
  75711. };
  75712. // colors shifting and distortion
  75713. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  75714. var _this = this;
  75715. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  75716. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  75717. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  75718. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75719. this._depthOfFieldPostProcess.onApply = function (effect) {
  75720. effect.setTexture("depthSampler", _this._depthTexture);
  75721. effect.setTexture("grainSampler", _this._grainTexture);
  75722. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  75723. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  75724. effect.setFloat('grain_amount', _this._grainAmount);
  75725. effect.setBool('blur_noise', _this._blurNoise);
  75726. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75727. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75728. effect.setFloat('distortion', _this._distortion);
  75729. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  75730. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  75731. effect.setFloat('aperture', _this._dofAperture);
  75732. effect.setFloat('darken', _this._dofDarken);
  75733. effect.setFloat('edge_blur', _this._edgeBlur);
  75734. effect.setBool('highlights', (_this._highlightsGain !== -1));
  75735. if (_this._scene.activeCamera) {
  75736. effect.setFloat('near', _this._scene.activeCamera.minZ);
  75737. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  75738. }
  75739. };
  75740. };
  75741. // creates a black and white random noise texture, 512x512
  75742. LensRenderingPipeline.prototype._createGrainTexture = function () {
  75743. var size = 512;
  75744. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75745. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75746. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75747. var context = this._grainTexture.getContext();
  75748. var rand = function (min, max) {
  75749. return Math.random() * (max - min) + min;
  75750. };
  75751. var value;
  75752. for (var x = 0; x < size; x++) {
  75753. for (var y = 0; y < size; y++) {
  75754. value = Math.floor(rand(0.42, 0.58) * 255);
  75755. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  75756. context.fillRect(x, y, 1, 1);
  75757. }
  75758. }
  75759. this._grainTexture.update(false);
  75760. };
  75761. return LensRenderingPipeline;
  75762. }(BABYLON.PostProcessRenderPipeline));
  75763. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  75764. })(BABYLON || (BABYLON = {}));
  75765. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  75766. var BABYLON;
  75767. (function (BABYLON) {
  75768. var StandardRenderingPipeline = /** @class */ (function (_super) {
  75769. __extends(StandardRenderingPipeline, _super);
  75770. /**
  75771. * @constructor
  75772. * @param {string} name - The rendering pipeline name
  75773. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75774. * @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)
  75775. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  75776. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75777. */
  75778. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  75779. if (originalPostProcess === void 0) { originalPostProcess = null; }
  75780. var _this = _super.call(this, scene.getEngine(), name) || this;
  75781. _this.downSampleX4PostProcess = null;
  75782. _this.brightPassPostProcess = null;
  75783. _this.blurHPostProcesses = [];
  75784. _this.blurVPostProcesses = [];
  75785. _this.textureAdderPostProcess = null;
  75786. _this.volumetricLightPostProcess = null;
  75787. _this.volumetricLightSmoothXPostProcess = null;
  75788. _this.volumetricLightSmoothYPostProcess = null;
  75789. _this.volumetricLightMergePostProces = null;
  75790. _this.volumetricLightFinalPostProcess = null;
  75791. _this.luminancePostProcess = null;
  75792. _this.luminanceDownSamplePostProcesses = [];
  75793. _this.hdrPostProcess = null;
  75794. _this.textureAdderFinalPostProcess = null;
  75795. _this.lensFlareFinalPostProcess = null;
  75796. _this.hdrFinalPostProcess = null;
  75797. _this.lensFlarePostProcess = null;
  75798. _this.lensFlareComposePostProcess = null;
  75799. _this.motionBlurPostProcess = null;
  75800. _this.depthOfFieldPostProcess = null;
  75801. // Values
  75802. _this.brightThreshold = 1.0;
  75803. _this.blurWidth = 512.0;
  75804. _this.horizontalBlur = false;
  75805. _this.exposure = 1.0;
  75806. _this.lensTexture = null;
  75807. _this.volumetricLightCoefficient = 0.2;
  75808. _this.volumetricLightPower = 4.0;
  75809. _this.volumetricLightBlurScale = 64.0;
  75810. _this.sourceLight = null;
  75811. _this.hdrMinimumLuminance = 1.0;
  75812. _this.hdrDecreaseRate = 0.5;
  75813. _this.hdrIncreaseRate = 0.5;
  75814. _this.lensColorTexture = null;
  75815. _this.lensFlareStrength = 20.0;
  75816. _this.lensFlareGhostDispersal = 1.4;
  75817. _this.lensFlareHaloWidth = 0.7;
  75818. _this.lensFlareDistortionStrength = 16.0;
  75819. _this.lensStarTexture = null;
  75820. _this.lensFlareDirtTexture = null;
  75821. _this.depthOfFieldDistance = 10.0;
  75822. _this.depthOfFieldBlurWidth = 64.0;
  75823. _this.motionStrength = 1.0;
  75824. // IAnimatable
  75825. _this.animations = [];
  75826. _this._currentDepthOfFieldSource = null;
  75827. _this._hdrCurrentLuminance = 1.0;
  75828. // Getters and setters
  75829. _this._bloomEnabled = true;
  75830. _this._depthOfFieldEnabled = false;
  75831. _this._vlsEnabled = false;
  75832. _this._lensFlareEnabled = false;
  75833. _this._hdrEnabled = false;
  75834. _this._motionBlurEnabled = false;
  75835. _this._motionBlurSamples = 64.0;
  75836. _this._volumetricLightStepsCount = 50.0;
  75837. _this._cameras = cameras || [];
  75838. // Initialize
  75839. _this._scene = scene;
  75840. _this._basePostProcess = originalPostProcess;
  75841. _this._ratio = ratio;
  75842. // Misc
  75843. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75844. // Finish
  75845. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75846. _this._buildPipeline();
  75847. return _this;
  75848. }
  75849. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  75850. get: function () {
  75851. return this._bloomEnabled;
  75852. },
  75853. set: function (enabled) {
  75854. if (this._bloomEnabled === enabled) {
  75855. return;
  75856. }
  75857. this._bloomEnabled = enabled;
  75858. this._buildPipeline();
  75859. },
  75860. enumerable: true,
  75861. configurable: true
  75862. });
  75863. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  75864. get: function () {
  75865. return this._depthOfFieldEnabled;
  75866. },
  75867. set: function (enabled) {
  75868. if (this._depthOfFieldEnabled === enabled) {
  75869. return;
  75870. }
  75871. this._depthOfFieldEnabled = enabled;
  75872. this._buildPipeline();
  75873. },
  75874. enumerable: true,
  75875. configurable: true
  75876. });
  75877. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  75878. get: function () {
  75879. return this._lensFlareEnabled;
  75880. },
  75881. set: function (enabled) {
  75882. if (this._lensFlareEnabled === enabled) {
  75883. return;
  75884. }
  75885. this._lensFlareEnabled = enabled;
  75886. this._buildPipeline();
  75887. },
  75888. enumerable: true,
  75889. configurable: true
  75890. });
  75891. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  75892. get: function () {
  75893. return this._hdrEnabled;
  75894. },
  75895. set: function (enabled) {
  75896. if (this._hdrEnabled === enabled) {
  75897. return;
  75898. }
  75899. this._hdrEnabled = enabled;
  75900. this._buildPipeline();
  75901. },
  75902. enumerable: true,
  75903. configurable: true
  75904. });
  75905. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  75906. get: function () {
  75907. return this._vlsEnabled;
  75908. },
  75909. set: function (enabled) {
  75910. if (this._vlsEnabled === enabled) {
  75911. return;
  75912. }
  75913. if (enabled) {
  75914. var geometry = this._scene.enableGeometryBufferRenderer();
  75915. if (!geometry) {
  75916. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  75917. return;
  75918. }
  75919. }
  75920. this._vlsEnabled = enabled;
  75921. this._buildPipeline();
  75922. },
  75923. enumerable: true,
  75924. configurable: true
  75925. });
  75926. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  75927. get: function () {
  75928. return this._motionBlurEnabled;
  75929. },
  75930. set: function (enabled) {
  75931. if (this._motionBlurEnabled === enabled) {
  75932. return;
  75933. }
  75934. this._motionBlurEnabled = enabled;
  75935. this._buildPipeline();
  75936. },
  75937. enumerable: true,
  75938. configurable: true
  75939. });
  75940. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  75941. get: function () {
  75942. return this._volumetricLightStepsCount;
  75943. },
  75944. set: function (count) {
  75945. if (this.volumetricLightPostProcess) {
  75946. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  75947. }
  75948. this._volumetricLightStepsCount = count;
  75949. },
  75950. enumerable: true,
  75951. configurable: true
  75952. });
  75953. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  75954. get: function () {
  75955. return this._motionBlurSamples;
  75956. },
  75957. set: function (samples) {
  75958. if (this.motionBlurPostProcess) {
  75959. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  75960. }
  75961. this._motionBlurSamples = samples;
  75962. },
  75963. enumerable: true,
  75964. configurable: true
  75965. });
  75966. StandardRenderingPipeline.prototype._buildPipeline = function () {
  75967. var _this = this;
  75968. var ratio = this._ratio;
  75969. var scene = this._scene;
  75970. this._disposePostProcesses();
  75971. this._reset();
  75972. // Create pass post-process
  75973. if (!this._basePostProcess) {
  75974. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  75975. this.originalPostProcess.onApply = function (effect) {
  75976. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  75977. };
  75978. }
  75979. else {
  75980. this.originalPostProcess = this._basePostProcess;
  75981. }
  75982. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  75983. this._currentDepthOfFieldSource = this.originalPostProcess;
  75984. if (this._bloomEnabled) {
  75985. // Create down sample X4 post-process
  75986. this._createDownSampleX4PostProcess(scene, ratio / 2);
  75987. // Create bright pass post-process
  75988. this._createBrightPassPostProcess(scene, ratio / 2);
  75989. // Create gaussian blur post-processes (down sampling blurs)
  75990. this._createBlurPostProcesses(scene, ratio / 4, 1);
  75991. // Create texture adder post-process
  75992. this._createTextureAdderPostProcess(scene, ratio);
  75993. // Create depth-of-field source post-process
  75994. 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);
  75995. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  75996. }
  75997. if (this._vlsEnabled) {
  75998. // Create volumetric light
  75999. this._createVolumetricLightPostProcess(scene, ratio);
  76000. // Create volumetric light final post-process
  76001. 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);
  76002. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  76003. }
  76004. if (this._lensFlareEnabled) {
  76005. // Create lens flare post-process
  76006. this._createLensFlarePostProcess(scene, ratio);
  76007. // Create depth-of-field source post-process post lens-flare and disable it now
  76008. 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);
  76009. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  76010. }
  76011. if (this._hdrEnabled) {
  76012. // Create luminance
  76013. this._createLuminancePostProcesses(scene, this._floatTextureType);
  76014. // Create HDR
  76015. this._createHdrPostProcess(scene, ratio);
  76016. // Create depth-of-field source post-process post hdr and disable it now
  76017. 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);
  76018. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  76019. }
  76020. if (this._depthOfFieldEnabled) {
  76021. // Create gaussian blur used by depth-of-field
  76022. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  76023. // Create depth-of-field post-process
  76024. this._createDepthOfFieldPostProcess(scene, ratio);
  76025. }
  76026. if (this._motionBlurEnabled) {
  76027. // Create motion blur post-process
  76028. this._createMotionBlurPostProcess(scene, ratio);
  76029. }
  76030. if (this._cameras !== null) {
  76031. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76032. }
  76033. };
  76034. // Down Sample X4 Post-Processs
  76035. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  76036. var _this = this;
  76037. var downSampleX4Offsets = new Array(32);
  76038. 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);
  76039. this.downSampleX4PostProcess.onApply = function (effect) {
  76040. var id = 0;
  76041. var width = _this.downSampleX4PostProcess.width;
  76042. var height = _this.downSampleX4PostProcess.height;
  76043. for (var i = -2; i < 2; i++) {
  76044. for (var j = -2; j < 2; j++) {
  76045. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  76046. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  76047. id += 2;
  76048. }
  76049. }
  76050. effect.setArray2("dsOffsets", downSampleX4Offsets);
  76051. };
  76052. // Add to pipeline
  76053. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  76054. };
  76055. // Brightpass Post-Process
  76056. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  76057. var _this = this;
  76058. var brightOffsets = new Array(8);
  76059. 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);
  76060. this.brightPassPostProcess.onApply = function (effect) {
  76061. var sU = (1.0 / _this.brightPassPostProcess.width);
  76062. var sV = (1.0 / _this.brightPassPostProcess.height);
  76063. brightOffsets[0] = -0.5 * sU;
  76064. brightOffsets[1] = 0.5 * sV;
  76065. brightOffsets[2] = 0.5 * sU;
  76066. brightOffsets[3] = 0.5 * sV;
  76067. brightOffsets[4] = -0.5 * sU;
  76068. brightOffsets[5] = -0.5 * sV;
  76069. brightOffsets[6] = 0.5 * sU;
  76070. brightOffsets[7] = -0.5 * sV;
  76071. effect.setArray2("dsOffsets", brightOffsets);
  76072. effect.setFloat("brightThreshold", _this.brightThreshold);
  76073. };
  76074. // Add to pipeline
  76075. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  76076. };
  76077. // Create blur H&V post-processes
  76078. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  76079. var _this = this;
  76080. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  76081. var engine = scene.getEngine();
  76082. 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);
  76083. 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);
  76084. blurX.onActivateObservable.add(function () {
  76085. var dw = blurX.width / engine.getRenderWidth();
  76086. blurX.kernel = _this[blurWidthKey] * dw;
  76087. });
  76088. blurY.onActivateObservable.add(function () {
  76089. var dw = blurY.height / engine.getRenderHeight();
  76090. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  76091. });
  76092. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  76093. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  76094. this.blurHPostProcesses.push(blurX);
  76095. this.blurVPostProcesses.push(blurY);
  76096. };
  76097. // Create texture adder post-process
  76098. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  76099. var _this = this;
  76100. 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);
  76101. this.textureAdderPostProcess.onApply = function (effect) {
  76102. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  76103. effect.setTexture("lensSampler", _this.lensTexture);
  76104. effect.setFloat("exposure", _this.exposure);
  76105. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  76106. };
  76107. // Add to pipeline
  76108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  76109. };
  76110. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  76111. var _this = this;
  76112. var geometryRenderer = scene.enableGeometryBufferRenderer();
  76113. geometryRenderer.enablePosition = true;
  76114. var geometry = geometryRenderer.getGBuffer();
  76115. // Base post-process
  76116. 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));
  76117. var depthValues = BABYLON.Vector2.Zero();
  76118. this.volumetricLightPostProcess.onApply = function (effect) {
  76119. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  76120. var generator = _this.sourceLight.getShadowGenerator();
  76121. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  76122. effect.setTexture("positionSampler", geometry.textures[2]);
  76123. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  76124. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  76125. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  76126. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  76127. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  76128. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  76129. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  76130. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  76131. effect.setVector2("depthValues", depthValues);
  76132. }
  76133. };
  76134. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  76135. // Smooth
  76136. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  76137. // Merge
  76138. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  76139. this.volumetricLightMergePostProces.onApply = function (effect) {
  76140. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  76141. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  76142. };
  76143. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  76144. };
  76145. // Create luminance
  76146. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  76147. var _this = this;
  76148. // Create luminance
  76149. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  76150. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  76151. var offsets = [];
  76152. this.luminancePostProcess.onApply = function (effect) {
  76153. var sU = (1.0 / _this.luminancePostProcess.width);
  76154. var sV = (1.0 / _this.luminancePostProcess.height);
  76155. offsets[0] = -0.5 * sU;
  76156. offsets[1] = 0.5 * sV;
  76157. offsets[2] = 0.5 * sU;
  76158. offsets[3] = 0.5 * sV;
  76159. offsets[4] = -0.5 * sU;
  76160. offsets[5] = -0.5 * sV;
  76161. offsets[6] = 0.5 * sU;
  76162. offsets[7] = -0.5 * sV;
  76163. effect.setArray2("lumOffsets", offsets);
  76164. };
  76165. // Add to pipeline
  76166. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  76167. // Create down sample luminance
  76168. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  76169. var size = Math.pow(3, i);
  76170. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  76171. if (i === 0) {
  76172. defines += "#define FINAL_DOWN_SAMPLER";
  76173. }
  76174. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  76175. this.luminanceDownSamplePostProcesses.push(postProcess);
  76176. }
  76177. // Create callbacks and add effects
  76178. var lastLuminance = this.luminancePostProcess;
  76179. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  76180. var downSampleOffsets = new Array(18);
  76181. pp.onApply = function (effect) {
  76182. if (!lastLuminance) {
  76183. return;
  76184. }
  76185. var id = 0;
  76186. for (var x = -1; x < 2; x++) {
  76187. for (var y = -1; y < 2; y++) {
  76188. downSampleOffsets[id] = x / lastLuminance.width;
  76189. downSampleOffsets[id + 1] = y / lastLuminance.height;
  76190. id += 2;
  76191. }
  76192. }
  76193. effect.setArray2("dsOffsets", downSampleOffsets);
  76194. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  76195. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76196. lastLuminance = _this.luminancePostProcess;
  76197. }
  76198. else {
  76199. lastLuminance = pp;
  76200. }
  76201. };
  76202. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76203. pp.onAfterRender = function (effect) {
  76204. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  76205. 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);
  76206. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  76207. };
  76208. }
  76209. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  76210. });
  76211. };
  76212. // Create HDR post-process
  76213. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  76214. var _this = this;
  76215. 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);
  76216. var outputLiminance = 1;
  76217. var time = 0;
  76218. var lastTime = 0;
  76219. this.hdrPostProcess.onApply = function (effect) {
  76220. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  76221. time += scene.getEngine().getDeltaTime();
  76222. if (outputLiminance < 0) {
  76223. outputLiminance = _this._hdrCurrentLuminance;
  76224. }
  76225. else {
  76226. var dt = (lastTime - time) / 1000.0;
  76227. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  76228. outputLiminance += _this.hdrDecreaseRate * dt;
  76229. }
  76230. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  76231. outputLiminance -= _this.hdrIncreaseRate * dt;
  76232. }
  76233. else {
  76234. outputLiminance = _this._hdrCurrentLuminance;
  76235. }
  76236. }
  76237. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  76238. effect.setFloat("averageLuminance", outputLiminance);
  76239. lastTime = time;
  76240. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  76241. };
  76242. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  76243. };
  76244. // Create lens flare post-process
  76245. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  76246. var _this = this;
  76247. 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);
  76248. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  76249. this._createBlurPostProcesses(scene, ratio / 4, 2);
  76250. 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);
  76251. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  76252. var resolution = new BABYLON.Vector2(0, 0);
  76253. // Lens flare
  76254. this.lensFlarePostProcess.onApply = function (effect) {
  76255. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  76256. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  76257. effect.setFloat("strength", _this.lensFlareStrength);
  76258. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  76259. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  76260. // Shift
  76261. resolution.x = _this.lensFlarePostProcess.width;
  76262. resolution.y = _this.lensFlarePostProcess.height;
  76263. effect.setVector2("resolution", resolution);
  76264. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  76265. };
  76266. // Compose
  76267. 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);
  76268. 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);
  76269. this.lensFlareComposePostProcess.onApply = function (effect) {
  76270. if (!_this._scene.activeCamera) {
  76271. return;
  76272. }
  76273. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76274. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  76275. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  76276. // Lens start rotation matrix
  76277. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  76278. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  76279. 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));
  76280. camRot *= 4.0;
  76281. 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);
  76282. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  76283. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  76284. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  76285. };
  76286. };
  76287. // Create depth-of-field post-process
  76288. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  76289. var _this = this;
  76290. 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);
  76291. this.depthOfFieldPostProcess.onApply = function (effect) {
  76292. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76293. effect.setTexture("depthSampler", _this._getDepthTexture());
  76294. effect.setFloat("distance", _this.depthOfFieldDistance);
  76295. };
  76296. // Add to pipeline
  76297. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  76298. };
  76299. // Create motion blur post-process
  76300. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  76301. var _this = this;
  76302. 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);
  76303. var motionScale = 0;
  76304. var prevViewProjection = BABYLON.Matrix.Identity();
  76305. var invViewProjection = BABYLON.Matrix.Identity();
  76306. var viewProjection = BABYLON.Matrix.Identity();
  76307. var screenSize = BABYLON.Vector2.Zero();
  76308. this.motionBlurPostProcess.onApply = function (effect) {
  76309. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  76310. viewProjection.invertToRef(invViewProjection);
  76311. effect.setMatrix("inverseViewProjection", invViewProjection);
  76312. effect.setMatrix("prevViewProjection", prevViewProjection);
  76313. prevViewProjection = viewProjection;
  76314. screenSize.x = _this.motionBlurPostProcess.width;
  76315. screenSize.y = _this.motionBlurPostProcess.height;
  76316. effect.setVector2("screenSize", screenSize);
  76317. motionScale = scene.getEngine().getFps() / 60.0;
  76318. effect.setFloat("motionScale", motionScale);
  76319. effect.setFloat("motionStrength", _this.motionStrength);
  76320. effect.setTexture("depthSampler", _this._getDepthTexture());
  76321. };
  76322. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  76323. };
  76324. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  76325. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  76326. var renderer = this._scene.enableGeometryBufferRenderer();
  76327. return renderer.getGBuffer().textures[0];
  76328. }
  76329. return this._scene.enableDepthRenderer().getDepthMap();
  76330. };
  76331. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  76332. for (var i = 0; i < this._cameras.length; i++) {
  76333. var camera = this._cameras[i];
  76334. if (this.originalPostProcess) {
  76335. this.originalPostProcess.dispose(camera);
  76336. }
  76337. if (this.downSampleX4PostProcess) {
  76338. this.downSampleX4PostProcess.dispose(camera);
  76339. }
  76340. if (this.brightPassPostProcess) {
  76341. this.brightPassPostProcess.dispose(camera);
  76342. }
  76343. if (this.textureAdderPostProcess) {
  76344. this.textureAdderPostProcess.dispose(camera);
  76345. }
  76346. if (this.textureAdderFinalPostProcess) {
  76347. this.textureAdderFinalPostProcess.dispose(camera);
  76348. }
  76349. if (this.volumetricLightPostProcess) {
  76350. this.volumetricLightPostProcess.dispose(camera);
  76351. }
  76352. if (this.volumetricLightSmoothXPostProcess) {
  76353. this.volumetricLightSmoothXPostProcess.dispose(camera);
  76354. }
  76355. if (this.volumetricLightSmoothYPostProcess) {
  76356. this.volumetricLightSmoothYPostProcess.dispose(camera);
  76357. }
  76358. if (this.volumetricLightMergePostProces) {
  76359. this.volumetricLightMergePostProces.dispose(camera);
  76360. }
  76361. if (this.volumetricLightFinalPostProcess) {
  76362. this.volumetricLightFinalPostProcess.dispose(camera);
  76363. }
  76364. if (this.lensFlarePostProcess) {
  76365. this.lensFlarePostProcess.dispose(camera);
  76366. }
  76367. if (this.lensFlareComposePostProcess) {
  76368. this.lensFlareComposePostProcess.dispose(camera);
  76369. }
  76370. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  76371. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  76372. }
  76373. if (this.luminancePostProcess) {
  76374. this.luminancePostProcess.dispose(camera);
  76375. }
  76376. if (this.hdrPostProcess) {
  76377. this.hdrPostProcess.dispose(camera);
  76378. }
  76379. if (this.hdrFinalPostProcess) {
  76380. this.hdrFinalPostProcess.dispose(camera);
  76381. }
  76382. if (this.depthOfFieldPostProcess) {
  76383. this.depthOfFieldPostProcess.dispose(camera);
  76384. }
  76385. if (this.motionBlurPostProcess) {
  76386. this.motionBlurPostProcess.dispose(camera);
  76387. }
  76388. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  76389. this.blurHPostProcesses[j].dispose(camera);
  76390. }
  76391. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  76392. this.blurVPostProcesses[j].dispose(camera);
  76393. }
  76394. }
  76395. this.originalPostProcess = null;
  76396. this.downSampleX4PostProcess = null;
  76397. this.brightPassPostProcess = null;
  76398. this.textureAdderPostProcess = null;
  76399. this.textureAdderFinalPostProcess = null;
  76400. this.volumetricLightPostProcess = null;
  76401. this.volumetricLightSmoothXPostProcess = null;
  76402. this.volumetricLightSmoothYPostProcess = null;
  76403. this.volumetricLightMergePostProces = null;
  76404. this.volumetricLightFinalPostProcess = null;
  76405. this.lensFlarePostProcess = null;
  76406. this.lensFlareComposePostProcess = null;
  76407. this.luminancePostProcess = null;
  76408. this.hdrPostProcess = null;
  76409. this.hdrFinalPostProcess = null;
  76410. this.depthOfFieldPostProcess = null;
  76411. this.motionBlurPostProcess = null;
  76412. this.luminanceDownSamplePostProcesses = [];
  76413. this.blurHPostProcesses = [];
  76414. this.blurVPostProcesses = [];
  76415. };
  76416. /**
  76417. * Dispose of the pipeline and stop all post processes
  76418. */
  76419. StandardRenderingPipeline.prototype.dispose = function () {
  76420. this._disposePostProcesses();
  76421. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76422. _super.prototype.dispose.call(this);
  76423. };
  76424. /**
  76425. * Serialize the rendering pipeline (Used when exporting)
  76426. * @returns the serialized object
  76427. */
  76428. StandardRenderingPipeline.prototype.serialize = function () {
  76429. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76430. if (this.sourceLight) {
  76431. serializationObject.sourceLightId = this.sourceLight.id;
  76432. }
  76433. serializationObject.customType = "StandardRenderingPipeline";
  76434. return serializationObject;
  76435. };
  76436. /**
  76437. * Parse the serialized pipeline
  76438. * @param source Source pipeline.
  76439. * @param scene The scene to load the pipeline to.
  76440. * @param rootUrl The URL of the serialized pipeline.
  76441. * @returns An instantiated pipeline from the serialized object.
  76442. */
  76443. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76444. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  76445. if (source.sourceLightId) {
  76446. p.sourceLight = scene.getLightByID(source.sourceLightId);
  76447. }
  76448. return p;
  76449. };
  76450. // Luminance steps
  76451. StandardRenderingPipeline.LuminanceSteps = 6;
  76452. __decorate([
  76453. BABYLON.serialize()
  76454. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  76455. __decorate([
  76456. BABYLON.serialize()
  76457. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  76458. __decorate([
  76459. BABYLON.serialize()
  76460. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  76461. __decorate([
  76462. BABYLON.serialize()
  76463. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  76464. __decorate([
  76465. BABYLON.serializeAsTexture("lensTexture")
  76466. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  76467. __decorate([
  76468. BABYLON.serialize()
  76469. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  76470. __decorate([
  76471. BABYLON.serialize()
  76472. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  76473. __decorate([
  76474. BABYLON.serialize()
  76475. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  76476. __decorate([
  76477. BABYLON.serialize()
  76478. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  76479. __decorate([
  76480. BABYLON.serialize()
  76481. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  76482. __decorate([
  76483. BABYLON.serialize()
  76484. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  76485. __decorate([
  76486. BABYLON.serializeAsTexture("lensColorTexture")
  76487. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  76488. __decorate([
  76489. BABYLON.serialize()
  76490. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  76491. __decorate([
  76492. BABYLON.serialize()
  76493. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  76494. __decorate([
  76495. BABYLON.serialize()
  76496. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  76497. __decorate([
  76498. BABYLON.serialize()
  76499. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  76500. __decorate([
  76501. BABYLON.serializeAsTexture("lensStarTexture")
  76502. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  76503. __decorate([
  76504. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  76505. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  76506. __decorate([
  76507. BABYLON.serialize()
  76508. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  76509. __decorate([
  76510. BABYLON.serialize()
  76511. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  76512. __decorate([
  76513. BABYLON.serialize()
  76514. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  76515. __decorate([
  76516. BABYLON.serialize()
  76517. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  76518. __decorate([
  76519. BABYLON.serialize()
  76520. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  76521. __decorate([
  76522. BABYLON.serialize()
  76523. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  76524. __decorate([
  76525. BABYLON.serialize()
  76526. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  76527. __decorate([
  76528. BABYLON.serialize()
  76529. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  76530. __decorate([
  76531. BABYLON.serialize()
  76532. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  76533. __decorate([
  76534. BABYLON.serialize()
  76535. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  76536. __decorate([
  76537. BABYLON.serialize()
  76538. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  76539. __decorate([
  76540. BABYLON.serialize()
  76541. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  76542. return StandardRenderingPipeline;
  76543. }(BABYLON.PostProcessRenderPipeline));
  76544. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  76545. })(BABYLON || (BABYLON = {}));
  76546. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  76547. var BABYLON;
  76548. (function (BABYLON) {
  76549. var FxaaPostProcess = /** @class */ (function (_super) {
  76550. __extends(FxaaPostProcess, _super);
  76551. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76552. if (camera === void 0) { camera = null; }
  76553. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76554. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  76555. var defines = _this._getDefines();
  76556. _this.updateEffect(defines);
  76557. _this.onApplyObservable.add(function (effect) {
  76558. var texelSize = _this.texelSize;
  76559. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  76560. });
  76561. return _this;
  76562. }
  76563. FxaaPostProcess.prototype._getDefines = function () {
  76564. var engine = this.getEngine();
  76565. if (!engine) {
  76566. return null;
  76567. }
  76568. var glInfo = engine.getGlInfo();
  76569. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  76570. return "#define MALI 1\n";
  76571. }
  76572. return null;
  76573. };
  76574. return FxaaPostProcess;
  76575. }(BABYLON.PostProcess));
  76576. BABYLON.FxaaPostProcess = FxaaPostProcess;
  76577. })(BABYLON || (BABYLON = {}));
  76578. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  76579. var BABYLON;
  76580. (function (BABYLON) {
  76581. /**
  76582. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  76583. */
  76584. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  76585. __extends(ChromaticAberrationPostProcess, _super);
  76586. /**
  76587. * Creates a new instance ChromaticAberrationPostProcess
  76588. * @param name The name of the effect.
  76589. * @param screenWidth The width of the screen to apply the effect on.
  76590. * @param screenHeight The height of the screen to apply the effect on.
  76591. * @param options The required width/height ratio to downsize to before computing the render pass.
  76592. * @param camera The camera to apply the render pass to.
  76593. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76594. * @param engine The engine which the post process will be applied. (default: current engine)
  76595. * @param reusable If the post process can be reused on the same frame. (default: false)
  76596. * @param textureType Type of textures used when performing the post process. (default: 0)
  76597. * @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)
  76598. */
  76599. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76600. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76601. if (blockCompilation === void 0) { blockCompilation = false; }
  76602. 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;
  76603. /**
  76604. * The amount of seperation of rgb channels (default: 30)
  76605. */
  76606. _this.aberrationAmount = 30;
  76607. /**
  76608. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  76609. */
  76610. _this.radialIntensity = 0;
  76611. /**
  76612. * 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))
  76613. */
  76614. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  76615. /**
  76616. * 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))
  76617. */
  76618. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  76619. _this.onApplyObservable.add(function (effect) {
  76620. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  76621. effect.setFloat('screen_width', screenWidth);
  76622. effect.setFloat('screen_height', screenHeight);
  76623. effect.setFloat('radialIntensity', _this.radialIntensity);
  76624. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  76625. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  76626. });
  76627. return _this;
  76628. }
  76629. return ChromaticAberrationPostProcess;
  76630. }(BABYLON.PostProcess));
  76631. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  76632. })(BABYLON || (BABYLON = {}));
  76633. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  76634. var BABYLON;
  76635. (function (BABYLON) {
  76636. /**
  76637. * The GrainPostProcess adds noise to the image at mid luminance levels
  76638. */
  76639. var GrainPostProcess = /** @class */ (function (_super) {
  76640. __extends(GrainPostProcess, _super);
  76641. /**
  76642. * Creates a new instance of @see GrainPostProcess
  76643. * @param name The name of the effect.
  76644. * @param options The required width/height ratio to downsize to before computing the render pass.
  76645. * @param camera The camera to apply the render pass to.
  76646. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76647. * @param engine The engine which the post process will be applied. (default: current engine)
  76648. * @param reusable If the post process can be reused on the same frame. (default: false)
  76649. * @param textureType Type of textures used when performing the post process. (default: 0)
  76650. * @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)
  76651. */
  76652. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76653. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76654. if (blockCompilation === void 0) { blockCompilation = false; }
  76655. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76656. /**
  76657. * The intensity of the grain added (default: 30)
  76658. */
  76659. _this.intensity = 30;
  76660. /**
  76661. * If the grain should be randomized on every frame
  76662. */
  76663. _this.animated = false;
  76664. _this.onApplyObservable.add(function (effect) {
  76665. effect.setFloat('intensity', _this.intensity);
  76666. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  76667. });
  76668. return _this;
  76669. }
  76670. return GrainPostProcess;
  76671. }(BABYLON.PostProcess));
  76672. BABYLON.GrainPostProcess = GrainPostProcess;
  76673. })(BABYLON || (BABYLON = {}));
  76674. //# sourceMappingURL=babylon.grainPostProcess.js.map
  76675. var BABYLON;
  76676. (function (BABYLON) {
  76677. /**
  76678. * The SharpenPostProcess applies a sharpen kernel to every pixel
  76679. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76680. */
  76681. var SharpenPostProcess = /** @class */ (function (_super) {
  76682. __extends(SharpenPostProcess, _super);
  76683. /**
  76684. * Creates a new instance ConvolutionPostProcess
  76685. * @param name The name of the effect.
  76686. * @param options The required width/height ratio to downsize to before computing the render pass.
  76687. * @param camera The camera to apply the render pass to.
  76688. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76689. * @param engine The engine which the post process will be applied. (default: current engine)
  76690. * @param reusable If the post process can be reused on the same frame. (default: false)
  76691. * @param textureType Type of textures used when performing the post process. (default: 0)
  76692. * @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)
  76693. */
  76694. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76695. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76696. if (blockCompilation === void 0) { blockCompilation = false; }
  76697. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76698. /**
  76699. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  76700. */
  76701. _this.colorAmount = 1.0;
  76702. /**
  76703. * How much sharpness should be applied (default: 0.3)
  76704. */
  76705. _this.edgeAmount = 0.3;
  76706. _this.onApply = function (effect) {
  76707. effect.setFloat2("screenSize", _this.width, _this.height);
  76708. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  76709. };
  76710. return _this;
  76711. }
  76712. return SharpenPostProcess;
  76713. }(BABYLON.PostProcess));
  76714. BABYLON.SharpenPostProcess = SharpenPostProcess;
  76715. })(BABYLON || (BABYLON = {}));
  76716. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  76717. var BABYLON;
  76718. (function (BABYLON) {
  76719. /**
  76720. * The Blur Post Process which blurs an image based on a kernel and direction.
  76721. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  76722. */
  76723. var BlurPostProcess = /** @class */ (function (_super) {
  76724. __extends(BlurPostProcess, _super);
  76725. /**
  76726. * Creates a new instance BlurPostProcess
  76727. * @param name The name of the effect.
  76728. * @param direction The direction in which to blur the image.
  76729. * @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.
  76730. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  76731. * @param camera The camera to apply the render pass to.
  76732. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76733. * @param engine The engine which the post process will be applied. (default: current engine)
  76734. * @param reusable If the post process can be reused on the same frame. (default: false)
  76735. * @param textureType Type of textures used when performing the post process. (default: 0)
  76736. * @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)
  76737. */
  76738. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  76739. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76740. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76741. if (defines === void 0) { defines = ""; }
  76742. if (blockCompilation === void 0) { blockCompilation = false; }
  76743. 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;
  76744. _this.direction = direction;
  76745. _this.blockCompilation = blockCompilation;
  76746. _this._packedFloat = false;
  76747. _this._staticDefines = "";
  76748. _this._staticDefines = defines;
  76749. _this.onApplyObservable.add(function (effect) {
  76750. if (_this._outputTexture) {
  76751. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  76752. }
  76753. else {
  76754. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  76755. }
  76756. });
  76757. _this.kernel = kernel;
  76758. return _this;
  76759. }
  76760. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  76761. /**
  76762. * Gets the length in pixels of the blur sample region
  76763. */
  76764. get: function () {
  76765. return this._idealKernel;
  76766. },
  76767. /**
  76768. * Sets the length in pixels of the blur sample region
  76769. */
  76770. set: function (v) {
  76771. if (this._idealKernel === v) {
  76772. return;
  76773. }
  76774. v = Math.max(v, 1);
  76775. this._idealKernel = v;
  76776. this._kernel = this._nearestBestKernel(v);
  76777. if (!this.blockCompilation) {
  76778. this._updateParameters();
  76779. }
  76780. },
  76781. enumerable: true,
  76782. configurable: true
  76783. });
  76784. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  76785. /**
  76786. * Gets wether or not the blur is unpacking/repacking floats
  76787. */
  76788. get: function () {
  76789. return this._packedFloat;
  76790. },
  76791. /**
  76792. * Sets wether or not the blur needs to unpack/repack floats
  76793. */
  76794. set: function (v) {
  76795. if (this._packedFloat === v) {
  76796. return;
  76797. }
  76798. this._packedFloat = v;
  76799. if (!this.blockCompilation) {
  76800. this._updateParameters();
  76801. }
  76802. },
  76803. enumerable: true,
  76804. configurable: true
  76805. });
  76806. /**
  76807. * Updates the effect with the current post process compile time values and recompiles the shader.
  76808. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76809. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76810. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76811. * @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
  76812. * @param onCompiled Called when the shader has been compiled.
  76813. * @param onError Called if there is an error when compiling a shader.
  76814. */
  76815. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76816. if (defines === void 0) { defines = null; }
  76817. if (uniforms === void 0) { uniforms = null; }
  76818. if (samplers === void 0) { samplers = null; }
  76819. this._updateParameters(onCompiled, onError);
  76820. };
  76821. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  76822. // Generate sampling offsets and weights
  76823. var N = this._kernel;
  76824. var centerIndex = (N - 1) / 2;
  76825. // Generate Gaussian sampling weights over kernel
  76826. var offsets = [];
  76827. var weights = [];
  76828. var totalWeight = 0;
  76829. for (var i = 0; i < N; i++) {
  76830. var u = i / (N - 1);
  76831. var w = this._gaussianWeight(u * 2.0 - 1);
  76832. offsets[i] = (i - centerIndex);
  76833. weights[i] = w;
  76834. totalWeight += w;
  76835. }
  76836. // Normalize weights
  76837. for (var i = 0; i < weights.length; i++) {
  76838. weights[i] /= totalWeight;
  76839. }
  76840. // Optimize: combine samples to take advantage of hardware linear sampling
  76841. // Walk from left to center, combining pairs (symmetrically)
  76842. var linearSamplingWeights = [];
  76843. var linearSamplingOffsets = [];
  76844. var linearSamplingMap = [];
  76845. for (var i = 0; i <= centerIndex; i += 2) {
  76846. var j = Math.min(i + 1, Math.floor(centerIndex));
  76847. var singleCenterSample = i === j;
  76848. if (singleCenterSample) {
  76849. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76850. }
  76851. else {
  76852. var sharedCell = j === centerIndex;
  76853. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  76854. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  76855. if (offsetLinear === 0) {
  76856. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76857. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  76858. }
  76859. else {
  76860. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  76861. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  76862. }
  76863. }
  76864. }
  76865. for (var i = 0; i < linearSamplingMap.length; i++) {
  76866. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  76867. linearSamplingWeights[i] = linearSamplingMap[i].w;
  76868. }
  76869. // Replace with optimized
  76870. offsets = linearSamplingOffsets;
  76871. weights = linearSamplingWeights;
  76872. // Generate shaders
  76873. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  76874. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  76875. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  76876. var defines = "";
  76877. defines += this._staticDefines;
  76878. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  76879. if (this._staticDefines.indexOf("DOF") != -1) {
  76880. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  76881. varyingCount--;
  76882. }
  76883. for (var i = 0; i < varyingCount; i++) {
  76884. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  76885. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  76886. }
  76887. var depCount = 0;
  76888. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  76889. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  76890. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  76891. depCount++;
  76892. }
  76893. if (this.packedFloat) {
  76894. defines += "#define PACKEDFLOAT 1";
  76895. }
  76896. this.blockCompilation = false;
  76897. _super.prototype.updateEffect.call(this, defines, null, null, {
  76898. varyingCount: varyingCount,
  76899. depCount: depCount
  76900. }, onCompiled, onError);
  76901. };
  76902. /**
  76903. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  76904. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  76905. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  76906. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  76907. * The gaps between physical kernels are compensated for in the weighting of the samples
  76908. * @param idealKernel Ideal blur kernel.
  76909. * @return Nearest best kernel.
  76910. */
  76911. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  76912. var v = Math.round(idealKernel);
  76913. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  76914. var k = _a[_i];
  76915. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  76916. return Math.max(k, 3);
  76917. }
  76918. }
  76919. return Math.max(v, 3);
  76920. };
  76921. /**
  76922. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  76923. * @param x The point on the Gaussian distribution to sample.
  76924. * @return the value of the Gaussian function at x.
  76925. */
  76926. BlurPostProcess.prototype._gaussianWeight = function (x) {
  76927. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  76928. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  76929. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  76930. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  76931. // truncated at around 1.3% of peak strength.
  76932. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  76933. var sigma = (1 / 3);
  76934. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  76935. var exponent = -((x * x) / (2.0 * sigma * sigma));
  76936. var weight = (1.0 / denominator) * Math.exp(exponent);
  76937. return weight;
  76938. };
  76939. /**
  76940. * Generates a string that can be used as a floating point number in GLSL.
  76941. * @param x Value to print.
  76942. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  76943. * @return GLSL float string.
  76944. */
  76945. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  76946. if (decimalFigures === void 0) { decimalFigures = 8; }
  76947. return x.toFixed(decimalFigures).replace(/0+$/, '');
  76948. };
  76949. return BlurPostProcess;
  76950. }(BABYLON.PostProcess));
  76951. BABYLON.BlurPostProcess = BlurPostProcess;
  76952. })(BABYLON || (BABYLON = {}));
  76953. //# sourceMappingURL=babylon.blurPostProcess.js.map
  76954. var BABYLON;
  76955. (function (BABYLON) {
  76956. /**
  76957. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  76958. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  76959. * based on samples that have a large difference in distance than the center pixel.
  76960. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  76961. */
  76962. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  76963. __extends(DepthOfFieldBlurPostProcess, _super);
  76964. /**
  76965. * Creates a new instance CircleOfConfusionPostProcess
  76966. * @param name The name of the effect.
  76967. * @param scene The scene the effect belongs to.
  76968. * @param direction The direction the blur should be applied.
  76969. * @param kernel The size of the kernel used to blur.
  76970. * @param options The required width/height ratio to downsize to before computing the render pass.
  76971. * @param camera The camera to apply the render pass to.
  76972. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  76973. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  76974. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76975. * @param engine The engine which the post process will be applied. (default: current engine)
  76976. * @param reusable If the post process can be reused on the same frame. (default: false)
  76977. * @param textureType Type of textures used when performing the post process. (default: 0)
  76978. * @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)
  76979. */
  76980. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  76981. if (imageToBlur === void 0) { imageToBlur = null; }
  76982. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76983. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76984. if (blockCompilation === void 0) { blockCompilation = false; }
  76985. 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;
  76986. _this.direction = direction;
  76987. _this.onApplyObservable.add(function (effect) {
  76988. if (imageToBlur != null) {
  76989. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  76990. }
  76991. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  76992. if (scene.activeCamera) {
  76993. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  76994. }
  76995. });
  76996. return _this;
  76997. }
  76998. return DepthOfFieldBlurPostProcess;
  76999. }(BABYLON.BlurPostProcess));
  77000. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  77001. })(BABYLON || (BABYLON = {}));
  77002. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  77003. var BABYLON;
  77004. (function (BABYLON) {
  77005. /**
  77006. * Options to be set when merging outputs from the default pipeline.
  77007. */
  77008. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  77009. function DepthOfFieldMergePostProcessOptions() {
  77010. }
  77011. return DepthOfFieldMergePostProcessOptions;
  77012. }());
  77013. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  77014. /**
  77015. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77016. */
  77017. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  77018. __extends(DepthOfFieldMergePostProcess, _super);
  77019. /**
  77020. * Creates a new instance of DepthOfFieldMergePostProcess
  77021. * @param name The name of the effect.
  77022. * @param originalFromInput Post process which's input will be used for the merge.
  77023. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  77024. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  77025. * @param options The required width/height ratio to downsize to before computing the render pass.
  77026. * @param camera The camera to apply the render pass to.
  77027. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77028. * @param engine The engine which the post process will be applied. (default: current engine)
  77029. * @param reusable If the post process can be reused on the same frame. (default: false)
  77030. * @param textureType Type of textures used when performing the post process. (default: 0)
  77031. * @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)
  77032. */
  77033. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77034. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77035. if (blockCompilation === void 0) { blockCompilation = false; }
  77036. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77037. _this.blurSteps = blurSteps;
  77038. _this.onApplyObservable.add(function (effect) {
  77039. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77040. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77041. blurSteps.forEach(function (step, index) {
  77042. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  77043. });
  77044. });
  77045. if (!blockCompilation) {
  77046. _this.updateEffect();
  77047. }
  77048. return _this;
  77049. }
  77050. /**
  77051. * Updates the effect with the current post process compile time values and recompiles the shader.
  77052. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  77053. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  77054. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  77055. * @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
  77056. * @param onCompiled Called when the shader has been compiled.
  77057. * @param onError Called if there is an error when compiling a shader.
  77058. */
  77059. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  77060. if (defines === void 0) { defines = null; }
  77061. if (uniforms === void 0) { uniforms = null; }
  77062. if (samplers === void 0) { samplers = null; }
  77063. if (!defines) {
  77064. defines = "";
  77065. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  77066. }
  77067. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  77068. };
  77069. return DepthOfFieldMergePostProcess;
  77070. }(BABYLON.PostProcess));
  77071. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  77072. })(BABYLON || (BABYLON = {}));
  77073. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  77074. var BABYLON;
  77075. (function (BABYLON) {
  77076. /**
  77077. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  77078. */
  77079. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  77080. __extends(CircleOfConfusionPostProcess, _super);
  77081. /**
  77082. * Creates a new instance CircleOfConfusionPostProcess
  77083. * @param name The name of the effect.
  77084. * @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.
  77085. * @param options The required width/height ratio to downsize to before computing the render pass.
  77086. * @param camera The camera to apply the render pass to.
  77087. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77088. * @param engine The engine which the post process will be applied. (default: current engine)
  77089. * @param reusable If the post process can be reused on the same frame. (default: false)
  77090. * @param textureType Type of textures used when performing the post process. (default: 0)
  77091. * @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)
  77092. */
  77093. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77094. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77095. if (blockCompilation === void 0) { blockCompilation = false; }
  77096. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77097. /**
  77098. * 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.
  77099. */
  77100. _this.lensSize = 50;
  77101. /**
  77102. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77103. */
  77104. _this.fStop = 1.4;
  77105. /**
  77106. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77107. */
  77108. _this.focusDistance = 2000;
  77109. /**
  77110. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  77111. */
  77112. _this.focalLength = 50;
  77113. _this._depthTexture = null;
  77114. _this._depthTexture = depthTexture;
  77115. _this.onApplyObservable.add(function (effect) {
  77116. if (!_this._depthTexture) {
  77117. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  77118. return;
  77119. }
  77120. effect.setTexture("depthSampler", _this._depthTexture);
  77121. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  77122. var aperture = _this.lensSize / _this.fStop;
  77123. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  77124. effect.setFloat('focusDistance', _this.focusDistance);
  77125. effect.setFloat('cocPrecalculation', cocPrecalculation);
  77126. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  77127. });
  77128. return _this;
  77129. }
  77130. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  77131. /**
  77132. * 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.
  77133. */
  77134. set: function (value) {
  77135. this._depthTexture = value;
  77136. },
  77137. enumerable: true,
  77138. configurable: true
  77139. });
  77140. return CircleOfConfusionPostProcess;
  77141. }(BABYLON.PostProcess));
  77142. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  77143. })(BABYLON || (BABYLON = {}));
  77144. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  77145. var BABYLON;
  77146. (function (BABYLON) {
  77147. /**
  77148. * Specifies the level of max blur that should be applied when using the depth of field effect
  77149. */
  77150. var DepthOfFieldEffectBlurLevel;
  77151. (function (DepthOfFieldEffectBlurLevel) {
  77152. /**
  77153. * Subtle blur
  77154. */
  77155. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  77156. /**
  77157. * Medium blur
  77158. */
  77159. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  77160. /**
  77161. * Large blur
  77162. */
  77163. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  77164. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  77165. ;
  77166. /**
  77167. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  77168. */
  77169. var DepthOfFieldEffect = /** @class */ (function (_super) {
  77170. __extends(DepthOfFieldEffect, _super);
  77171. /**
  77172. * Creates a new instance DepthOfFieldEffect
  77173. * @param scene The scene the effect belongs to.
  77174. * @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.
  77175. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77176. * @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)
  77177. */
  77178. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  77179. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  77180. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77181. if (blockCompilation === void 0) { blockCompilation = false; }
  77182. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  77183. return _this._effects;
  77184. }, true) || this;
  77185. /**
  77186. * Internal post processes in depth of field effect
  77187. */
  77188. _this._effects = [];
  77189. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  77190. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77191. // 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)
  77192. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  77193. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77194. _this._depthOfFieldBlurY = [];
  77195. _this._depthOfFieldBlurX = [];
  77196. var blurCount = 1;
  77197. var kernelSize = 15;
  77198. switch (blurLevel) {
  77199. case DepthOfFieldEffectBlurLevel.High: {
  77200. blurCount = 3;
  77201. kernelSize = 51;
  77202. break;
  77203. }
  77204. case DepthOfFieldEffectBlurLevel.Medium: {
  77205. blurCount = 2;
  77206. kernelSize = 31;
  77207. break;
  77208. }
  77209. default: {
  77210. kernelSize = 15;
  77211. blurCount = 1;
  77212. break;
  77213. }
  77214. }
  77215. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  77216. var ratio = 1.0;
  77217. for (var i = 0; i < blurCount; i++) {
  77218. 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);
  77219. blurY.autoClear = false;
  77220. ratio = 0.75 / Math.pow(2, i);
  77221. 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);
  77222. blurX.autoClear = false;
  77223. _this._depthOfFieldBlurY.push(blurY);
  77224. _this._depthOfFieldBlurX.push(blurX);
  77225. }
  77226. // Set all post processes on the effect.
  77227. _this._effects = [_this._circleOfConfusion];
  77228. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  77229. _this._effects.push(_this._depthOfFieldBlurY[i]);
  77230. _this._effects.push(_this._depthOfFieldBlurX[i]);
  77231. }
  77232. // Merge blurred images with original image based on circleOfConfusion
  77233. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77234. _this._dofMerge.autoClear = false;
  77235. _this._effects.push(_this._dofMerge);
  77236. return _this;
  77237. }
  77238. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  77239. get: function () {
  77240. return this._circleOfConfusion.focalLength;
  77241. },
  77242. /**
  77243. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  77244. */
  77245. set: function (value) {
  77246. this._circleOfConfusion.focalLength = value;
  77247. },
  77248. enumerable: true,
  77249. configurable: true
  77250. });
  77251. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  77252. get: function () {
  77253. return this._circleOfConfusion.fStop;
  77254. },
  77255. /**
  77256. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77257. */
  77258. set: function (value) {
  77259. this._circleOfConfusion.fStop = value;
  77260. },
  77261. enumerable: true,
  77262. configurable: true
  77263. });
  77264. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  77265. get: function () {
  77266. return this._circleOfConfusion.focusDistance;
  77267. },
  77268. /**
  77269. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77270. */
  77271. set: function (value) {
  77272. this._circleOfConfusion.focusDistance = value;
  77273. },
  77274. enumerable: true,
  77275. configurable: true
  77276. });
  77277. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  77278. get: function () {
  77279. return this._circleOfConfusion.lensSize;
  77280. },
  77281. /**
  77282. * 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.
  77283. */
  77284. set: function (value) {
  77285. this._circleOfConfusion.lensSize = value;
  77286. },
  77287. enumerable: true,
  77288. configurable: true
  77289. });
  77290. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  77291. /**
  77292. * 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.
  77293. */
  77294. set: function (value) {
  77295. this._circleOfConfusion.depthTexture = value;
  77296. },
  77297. enumerable: true,
  77298. configurable: true
  77299. });
  77300. /**
  77301. * Disposes each of the internal effects for a given camera.
  77302. * @param camera The camera to dispose the effect on.
  77303. */
  77304. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  77305. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77306. this._effects[effectIndex].dispose(camera);
  77307. }
  77308. };
  77309. /**
  77310. * Internal
  77311. */
  77312. DepthOfFieldEffect.prototype._updateEffects = function () {
  77313. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77314. this._effects[effectIndex].updateEffect();
  77315. }
  77316. };
  77317. /**
  77318. * Internal
  77319. * @returns if all the contained post processes are ready.
  77320. */
  77321. DepthOfFieldEffect.prototype._isReady = function () {
  77322. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77323. if (!this._effects[effectIndex].isReady()) {
  77324. return false;
  77325. }
  77326. }
  77327. return true;
  77328. };
  77329. return DepthOfFieldEffect;
  77330. }(BABYLON.PostProcessRenderEffect));
  77331. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  77332. })(BABYLON || (BABYLON = {}));
  77333. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  77334. var BABYLON;
  77335. (function (BABYLON) {
  77336. /**
  77337. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77338. */
  77339. var BloomMergePostProcess = /** @class */ (function (_super) {
  77340. __extends(BloomMergePostProcess, _super);
  77341. /**
  77342. * Creates a new instance of @see BloomMergePostProcess
  77343. * @param name The name of the effect.
  77344. * @param originalFromInput Post process which's input will be used for the merge.
  77345. * @param blurred Blurred highlights post process which's output will be used.
  77346. * @param weight Weight of the bloom to be added to the original input.
  77347. * @param options The required width/height ratio to downsize to before computing the render pass.
  77348. * @param camera The camera to apply the render pass to.
  77349. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77350. * @param engine The engine which the post process will be applied. (default: current engine)
  77351. * @param reusable If the post process can be reused on the same frame. (default: false)
  77352. * @param textureType Type of textures used when performing the post process. (default: 0)
  77353. * @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)
  77354. */
  77355. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77356. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77357. if (blockCompilation === void 0) { blockCompilation = false; }
  77358. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77359. _this.weight = weight;
  77360. _this.onApplyObservable.add(function (effect) {
  77361. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77362. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  77363. effect.setFloat("bloomWeight", _this.weight);
  77364. });
  77365. if (!blockCompilation) {
  77366. _this.updateEffect();
  77367. }
  77368. return _this;
  77369. }
  77370. return BloomMergePostProcess;
  77371. }(BABYLON.PostProcess));
  77372. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  77373. })(BABYLON || (BABYLON = {}));
  77374. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  77375. var BABYLON;
  77376. (function (BABYLON) {
  77377. /**
  77378. * 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.
  77379. */
  77380. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  77381. __extends(ExtractHighlightsPostProcess, _super);
  77382. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77383. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77384. if (blockCompilation === void 0) { blockCompilation = false; }
  77385. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77386. /**
  77387. * The luminance threshold, pixels below this value will be set to black.
  77388. */
  77389. _this.threshold = 0.9;
  77390. /**
  77391. * Internal
  77392. */
  77393. _this._exposure = 1;
  77394. /**
  77395. * Post process which has the input texture to be used when performing highlight extraction
  77396. */
  77397. _this._inputPostProcess = null;
  77398. _this.onApplyObservable.add(function (effect) {
  77399. if (_this._inputPostProcess) {
  77400. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  77401. }
  77402. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  77403. effect.setFloat('exposure', _this._exposure);
  77404. });
  77405. return _this;
  77406. }
  77407. return ExtractHighlightsPostProcess;
  77408. }(BABYLON.PostProcess));
  77409. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  77410. })(BABYLON || (BABYLON = {}));
  77411. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  77412. var BABYLON;
  77413. (function (BABYLON) {
  77414. /**
  77415. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  77416. */
  77417. var BloomEffect = /** @class */ (function (_super) {
  77418. __extends(BloomEffect, _super);
  77419. /**
  77420. * Creates a new instance of @see BloomEffect
  77421. * @param scene The scene the effect belongs to.
  77422. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  77423. * @param bloomKernel The size of the kernel to be used when applying the blur.
  77424. * @param bloomWeight The the strength of bloom.
  77425. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77426. * @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)
  77427. */
  77428. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  77429. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77430. if (blockCompilation === void 0) { blockCompilation = false; }
  77431. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  77432. return _this._effects;
  77433. }, true) || this;
  77434. _this.bloomScale = bloomScale;
  77435. /**
  77436. * Internal
  77437. */
  77438. _this._effects = [];
  77439. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77440. _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);
  77441. _this._blurX.alwaysForcePOT = true;
  77442. _this._blurX.autoClear = false;
  77443. _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);
  77444. _this._blurY.alwaysForcePOT = true;
  77445. _this._blurY.autoClear = false;
  77446. _this.kernel = bloomKernel;
  77447. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  77448. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77449. _this._merge.autoClear = false;
  77450. _this._effects.push(_this._merge);
  77451. return _this;
  77452. }
  77453. Object.defineProperty(BloomEffect.prototype, "threshold", {
  77454. /**
  77455. * The luminance threshold to find bright areas of the image to bloom.
  77456. */
  77457. get: function () {
  77458. return this._downscale.threshold;
  77459. },
  77460. set: function (value) {
  77461. this._downscale.threshold = value;
  77462. },
  77463. enumerable: true,
  77464. configurable: true
  77465. });
  77466. Object.defineProperty(BloomEffect.prototype, "weight", {
  77467. /**
  77468. * The strength of the bloom.
  77469. */
  77470. get: function () {
  77471. return this._merge.weight;
  77472. },
  77473. set: function (value) {
  77474. this._merge.weight = value;
  77475. },
  77476. enumerable: true,
  77477. configurable: true
  77478. });
  77479. Object.defineProperty(BloomEffect.prototype, "kernel", {
  77480. /**
  77481. * Specifies the size of the bloom blur kernel, relative to the final output size
  77482. */
  77483. get: function () {
  77484. return this._blurX.kernel / this.bloomScale;
  77485. },
  77486. set: function (value) {
  77487. this._blurX.kernel = value * this.bloomScale;
  77488. this._blurY.kernel = value * this.bloomScale;
  77489. },
  77490. enumerable: true,
  77491. configurable: true
  77492. });
  77493. /**
  77494. * Disposes each of the internal effects for a given camera.
  77495. * @param camera The camera to dispose the effect on.
  77496. */
  77497. BloomEffect.prototype.disposeEffects = function (camera) {
  77498. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77499. this._effects[effectIndex].dispose(camera);
  77500. }
  77501. };
  77502. /**
  77503. * Internal
  77504. */
  77505. BloomEffect.prototype._updateEffects = function () {
  77506. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77507. this._effects[effectIndex].updateEffect();
  77508. }
  77509. };
  77510. /**
  77511. * Internal
  77512. * @returns if all the contained post processes are ready.
  77513. */
  77514. BloomEffect.prototype._isReady = function () {
  77515. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77516. if (!this._effects[effectIndex].isReady()) {
  77517. return false;
  77518. }
  77519. }
  77520. return true;
  77521. };
  77522. return BloomEffect;
  77523. }(BABYLON.PostProcessRenderEffect));
  77524. BABYLON.BloomEffect = BloomEffect;
  77525. })(BABYLON || (BABYLON = {}));
  77526. //# sourceMappingURL=babylon.bloomEffect.js.map
  77527. var BABYLON;
  77528. (function (BABYLON) {
  77529. /**
  77530. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  77531. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  77532. */
  77533. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  77534. __extends(DefaultRenderingPipeline, _super);
  77535. /**
  77536. * @constructor
  77537. * @param {string} name - The rendering pipeline name (default: "")
  77538. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  77539. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  77540. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  77541. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  77542. */
  77543. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  77544. if (name === void 0) { name = ""; }
  77545. if (hdr === void 0) { hdr = true; }
  77546. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77547. if (automaticBuild === void 0) { automaticBuild = true; }
  77548. var _this = _super.call(this, scene.getEngine(), name) || this;
  77549. _this._camerasToBeAttached = [];
  77550. /**
  77551. * ID of the sharpen post process,
  77552. */
  77553. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  77554. /**
  77555. * ID of the image processing post process;
  77556. */
  77557. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  77558. /**
  77559. * ID of the Fast Approximate Anti-Aliasing post process;
  77560. */
  77561. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  77562. /**
  77563. * ID of the chromatic aberration post process,
  77564. */
  77565. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  77566. /**
  77567. * ID of the grain post process
  77568. */
  77569. _this.GrainPostProcessId = "GrainPostProcessEffect";
  77570. /**
  77571. * Glow post process which adds a glow to emmisive areas of the image
  77572. */
  77573. _this._glowLayer = null;
  77574. /**
  77575. * Animations which can be used to tweak settings over a period of time
  77576. */
  77577. _this.animations = [];
  77578. _this._imageProcessingConfigurationObserver = null;
  77579. // Values
  77580. _this._sharpenEnabled = false;
  77581. _this._bloomEnabled = false;
  77582. _this._depthOfFieldEnabled = false;
  77583. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  77584. _this._fxaaEnabled = false;
  77585. _this._imageProcessingEnabled = true;
  77586. _this._bloomScale = 0.5;
  77587. _this._chromaticAberrationEnabled = false;
  77588. _this._grainEnabled = false;
  77589. _this._buildAllowed = true;
  77590. _this._resizeObserver = null;
  77591. _this._hardwareScaleLevel = 1.0;
  77592. _this._bloomKernel = 64;
  77593. /**
  77594. * Specifies the weight of the bloom in the final rendering
  77595. */
  77596. _this._bloomWeight = 0.15;
  77597. /**
  77598. * Specifies the luma threshold for the area that will be blurred by the bloom
  77599. */
  77600. _this._bloomThreshold = 0.9;
  77601. _this._samples = 1;
  77602. _this._hasCleared = false;
  77603. _this._prevPostProcess = null;
  77604. _this._prevPrevPostProcess = null;
  77605. _this._cameras = cameras || scene.cameras;
  77606. _this._camerasToBeAttached = _this._cameras.slice();
  77607. _this._buildAllowed = automaticBuild;
  77608. // Initialize
  77609. _this._scene = scene;
  77610. var caps = _this._scene.getEngine().getCaps();
  77611. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  77612. // Misc
  77613. if (_this._hdr) {
  77614. if (caps.textureHalfFloatRender) {
  77615. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77616. }
  77617. else if (caps.textureFloatRender) {
  77618. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77619. }
  77620. }
  77621. else {
  77622. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77623. }
  77624. // Attach
  77625. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77626. var engine = _this._scene.getEngine();
  77627. // Create post processes before hand so they can be modified before enabled.
  77628. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  77629. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77630. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  77631. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  77632. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  77633. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77634. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  77635. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77636. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  77637. _this._resizeObserver = engine.onResizeObservable.add(function () {
  77638. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  77639. _this.bloomKernel = _this.bloomKernel;
  77640. });
  77641. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  77642. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  77643. });
  77644. _this._buildPipeline();
  77645. return _this;
  77646. }
  77647. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  77648. get: function () {
  77649. return this._sharpenEnabled;
  77650. },
  77651. /**
  77652. * Enable or disable the sharpen process from the pipeline
  77653. */
  77654. set: function (enabled) {
  77655. if (this._sharpenEnabled === enabled) {
  77656. return;
  77657. }
  77658. this._sharpenEnabled = enabled;
  77659. this._buildPipeline();
  77660. },
  77661. enumerable: true,
  77662. configurable: true
  77663. });
  77664. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  77665. /**
  77666. * Specifies the size of the bloom blur kernel, relative to the final output size
  77667. */
  77668. get: function () {
  77669. return this._bloomKernel;
  77670. },
  77671. set: function (value) {
  77672. this._bloomKernel = value;
  77673. this.bloom.kernel = value / this._hardwareScaleLevel;
  77674. },
  77675. enumerable: true,
  77676. configurable: true
  77677. });
  77678. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  77679. get: function () {
  77680. return this._bloomWeight;
  77681. },
  77682. /**
  77683. * The strength of the bloom.
  77684. */
  77685. set: function (value) {
  77686. if (this._bloomWeight === value) {
  77687. return;
  77688. }
  77689. this.bloom.weight = value;
  77690. this._bloomWeight = value;
  77691. },
  77692. enumerable: true,
  77693. configurable: true
  77694. });
  77695. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  77696. get: function () {
  77697. return this._bloomThreshold;
  77698. },
  77699. /**
  77700. * The strength of the bloom.
  77701. */
  77702. set: function (value) {
  77703. if (this._bloomThreshold === value) {
  77704. return;
  77705. }
  77706. this.bloom.threshold = value;
  77707. this._bloomThreshold = value;
  77708. },
  77709. enumerable: true,
  77710. configurable: true
  77711. });
  77712. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  77713. get: function () {
  77714. return this._bloomScale;
  77715. },
  77716. /**
  77717. * The scale of the bloom, lower value will provide better performance.
  77718. */
  77719. set: function (value) {
  77720. if (this._bloomScale === value) {
  77721. return;
  77722. }
  77723. this._bloomScale = value;
  77724. // recreate bloom and dispose old as this setting is not dynamic
  77725. this._rebuildBloom();
  77726. this._buildPipeline();
  77727. },
  77728. enumerable: true,
  77729. configurable: true
  77730. });
  77731. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  77732. get: function () {
  77733. return this._bloomEnabled;
  77734. },
  77735. /**
  77736. * Enable or disable the bloom from the pipeline
  77737. */
  77738. set: function (enabled) {
  77739. if (this._bloomEnabled === enabled) {
  77740. return;
  77741. }
  77742. this._bloomEnabled = enabled;
  77743. this._buildPipeline();
  77744. },
  77745. enumerable: true,
  77746. configurable: true
  77747. });
  77748. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  77749. // recreate bloom and dispose old as this setting is not dynamic
  77750. var oldBloom = this.bloom;
  77751. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  77752. this.bloom.threshold = oldBloom.threshold;
  77753. for (var i = 0; i < this._cameras.length; i++) {
  77754. oldBloom.disposeEffects(this._cameras[i]);
  77755. }
  77756. };
  77757. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  77758. /**
  77759. * If the depth of field is enabled.
  77760. */
  77761. get: function () {
  77762. return this._depthOfFieldEnabled;
  77763. },
  77764. set: function (enabled) {
  77765. if (this._depthOfFieldEnabled === enabled) {
  77766. return;
  77767. }
  77768. this._depthOfFieldEnabled = enabled;
  77769. this._buildPipeline();
  77770. },
  77771. enumerable: true,
  77772. configurable: true
  77773. });
  77774. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  77775. /**
  77776. * Blur level of the depth of field effect. (Higher blur will effect performance)
  77777. */
  77778. get: function () {
  77779. return this._depthOfFieldBlurLevel;
  77780. },
  77781. set: function (value) {
  77782. if (this._depthOfFieldBlurLevel === value) {
  77783. return;
  77784. }
  77785. this._depthOfFieldBlurLevel = value;
  77786. // recreate dof and dispose old as this setting is not dynamic
  77787. var oldDof = this.depthOfField;
  77788. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  77789. this.depthOfField.focalLength = oldDof.focalLength;
  77790. this.depthOfField.focusDistance = oldDof.focusDistance;
  77791. this.depthOfField.fStop = oldDof.fStop;
  77792. this.depthOfField.lensSize = oldDof.lensSize;
  77793. for (var i = 0; i < this._cameras.length; i++) {
  77794. oldDof.disposeEffects(this._cameras[i]);
  77795. }
  77796. this._buildPipeline();
  77797. },
  77798. enumerable: true,
  77799. configurable: true
  77800. });
  77801. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  77802. get: function () {
  77803. return this._fxaaEnabled;
  77804. },
  77805. /**
  77806. * If the anti aliasing is enabled.
  77807. */
  77808. set: function (enabled) {
  77809. if (this._fxaaEnabled === enabled) {
  77810. return;
  77811. }
  77812. this._fxaaEnabled = enabled;
  77813. this._buildPipeline();
  77814. },
  77815. enumerable: true,
  77816. configurable: true
  77817. });
  77818. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  77819. get: function () {
  77820. return this._samples;
  77821. },
  77822. /**
  77823. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  77824. */
  77825. set: function (sampleCount) {
  77826. if (this._samples === sampleCount) {
  77827. return;
  77828. }
  77829. this._samples = sampleCount;
  77830. this._buildPipeline();
  77831. },
  77832. enumerable: true,
  77833. configurable: true
  77834. });
  77835. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  77836. get: function () {
  77837. return this._imageProcessingEnabled;
  77838. },
  77839. /**
  77840. * If image processing is enabled.
  77841. */
  77842. set: function (enabled) {
  77843. if (this._imageProcessingEnabled === enabled) {
  77844. return;
  77845. }
  77846. this._imageProcessingEnabled = enabled;
  77847. this._buildPipeline();
  77848. },
  77849. enumerable: true,
  77850. configurable: true
  77851. });
  77852. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  77853. get: function () {
  77854. return this._glowLayer == null;
  77855. },
  77856. /**
  77857. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  77858. */
  77859. set: function (enabled) {
  77860. if (enabled && !this._glowLayer) {
  77861. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  77862. }
  77863. else if (!enabled && this._glowLayer) {
  77864. this._glowLayer.dispose();
  77865. this._glowLayer = null;
  77866. }
  77867. },
  77868. enumerable: true,
  77869. configurable: true
  77870. });
  77871. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  77872. get: function () {
  77873. return this._chromaticAberrationEnabled;
  77874. },
  77875. /**
  77876. * Enable or disable the chromaticAberration process from the pipeline
  77877. */
  77878. set: function (enabled) {
  77879. if (this._chromaticAberrationEnabled === enabled) {
  77880. return;
  77881. }
  77882. this._chromaticAberrationEnabled = enabled;
  77883. this._buildPipeline();
  77884. },
  77885. enumerable: true,
  77886. configurable: true
  77887. });
  77888. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  77889. get: function () {
  77890. return this._grainEnabled;
  77891. },
  77892. /**
  77893. * Enable or disable the grain process from the pipeline
  77894. */
  77895. set: function (enabled) {
  77896. if (this._grainEnabled === enabled) {
  77897. return;
  77898. }
  77899. this._grainEnabled = enabled;
  77900. this._buildPipeline();
  77901. },
  77902. enumerable: true,
  77903. configurable: true
  77904. });
  77905. /**
  77906. * Force the compilation of the entire pipeline.
  77907. */
  77908. DefaultRenderingPipeline.prototype.prepare = function () {
  77909. var previousState = this._buildAllowed;
  77910. this._buildAllowed = true;
  77911. this._buildPipeline();
  77912. this._buildAllowed = previousState;
  77913. };
  77914. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  77915. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  77916. if (this._hasCleared) {
  77917. postProcess.autoClear = false;
  77918. }
  77919. else {
  77920. postProcess.autoClear = true;
  77921. this._scene.autoClear = false;
  77922. this._hasCleared = true;
  77923. }
  77924. if (!skipTextureSharing) {
  77925. if (this._prevPrevPostProcess) {
  77926. postProcess.shareOutputWith(this._prevPrevPostProcess);
  77927. }
  77928. else {
  77929. postProcess.useOwnOutput();
  77930. }
  77931. if (this._prevPostProcess) {
  77932. this._prevPrevPostProcess = this._prevPostProcess;
  77933. }
  77934. this._prevPostProcess = postProcess;
  77935. }
  77936. };
  77937. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  77938. var _this = this;
  77939. if (!this._buildAllowed) {
  77940. return;
  77941. }
  77942. this._scene.autoClear = true;
  77943. var engine = this._scene.getEngine();
  77944. this._disposePostProcesses();
  77945. if (this._cameras !== null) {
  77946. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77947. // get back cameras to be used to reattach pipeline
  77948. this._cameras = this._camerasToBeAttached.slice();
  77949. }
  77950. this._reset();
  77951. this._prevPostProcess = null;
  77952. this._prevPrevPostProcess = null;
  77953. this._hasCleared = false;
  77954. if (this.depthOfFieldEnabled) {
  77955. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  77956. this.depthOfField.depthTexture = depthTexture;
  77957. if (!this.depthOfField._isReady()) {
  77958. this.depthOfField._updateEffects();
  77959. }
  77960. this.addEffect(this.depthOfField);
  77961. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  77962. }
  77963. if (this.bloomEnabled) {
  77964. if (!this.bloom._isReady()) {
  77965. this.bloom._updateEffects();
  77966. }
  77967. this.addEffect(this.bloom);
  77968. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  77969. }
  77970. if (this._imageProcessingEnabled) {
  77971. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  77972. if (this._hdr) {
  77973. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  77974. this._setAutoClearAndTextureSharing(this.imageProcessing);
  77975. }
  77976. else {
  77977. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  77978. }
  77979. }
  77980. if (this.sharpenEnabled) {
  77981. if (!this.sharpen.isReady()) {
  77982. this.sharpen.updateEffect();
  77983. }
  77984. this.addEffect(this._sharpenEffect);
  77985. this._setAutoClearAndTextureSharing(this.sharpen);
  77986. }
  77987. if (this.grainEnabled) {
  77988. if (!this.grain.isReady()) {
  77989. this.grain.updateEffect();
  77990. }
  77991. this.addEffect(this._grainEffect);
  77992. this._setAutoClearAndTextureSharing(this.grain);
  77993. }
  77994. if (this.chromaticAberrationEnabled) {
  77995. if (!this.chromaticAberration.isReady()) {
  77996. this.chromaticAberration.updateEffect();
  77997. }
  77998. this.addEffect(this._chromaticAberrationEffect);
  77999. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  78000. }
  78001. if (this.fxaaEnabled) {
  78002. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78003. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  78004. this._setAutoClearAndTextureSharing(this.fxaa, true);
  78005. }
  78006. if (this._cameras !== null) {
  78007. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78008. }
  78009. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  78010. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  78011. }
  78012. };
  78013. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  78014. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  78015. for (var i = 0; i < this._cameras.length; i++) {
  78016. var camera = this._cameras[i];
  78017. if (this.imageProcessing) {
  78018. this.imageProcessing.dispose(camera);
  78019. }
  78020. if (this.fxaa) {
  78021. this.fxaa.dispose(camera);
  78022. }
  78023. // These are created in the constructor and should not be disposed on every pipeline change
  78024. if (disposeNonRecreated) {
  78025. if (this.sharpen) {
  78026. this.sharpen.dispose(camera);
  78027. }
  78028. if (this.depthOfField) {
  78029. this.depthOfField.disposeEffects(camera);
  78030. }
  78031. if (this.bloom) {
  78032. this.bloom.disposeEffects(camera);
  78033. }
  78034. if (this.chromaticAberration) {
  78035. this.chromaticAberration.dispose(camera);
  78036. }
  78037. if (this.grain) {
  78038. this.grain.dispose(camera);
  78039. }
  78040. if (this._glowLayer) {
  78041. this._glowLayer.dispose();
  78042. }
  78043. }
  78044. }
  78045. this.imageProcessing = null;
  78046. this.fxaa = null;
  78047. if (disposeNonRecreated) {
  78048. this.sharpen = null;
  78049. this._sharpenEffect = null;
  78050. this.depthOfField = null;
  78051. this.bloom = null;
  78052. this.chromaticAberration = null;
  78053. this._chromaticAberrationEffect = null;
  78054. this.grain = null;
  78055. this._grainEffect = null;
  78056. this._glowLayer = null;
  78057. }
  78058. };
  78059. /**
  78060. * Adds a camera to the pipeline
  78061. * @param camera the camera to be added
  78062. */
  78063. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  78064. this._camerasToBeAttached.push(camera);
  78065. this._buildPipeline();
  78066. };
  78067. /**
  78068. * Removes a camera from the pipeline
  78069. * @param camera the camera to remove
  78070. */
  78071. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  78072. var index = this._camerasToBeAttached.indexOf(camera);
  78073. this._camerasToBeAttached.splice(index, 1);
  78074. this._buildPipeline();
  78075. };
  78076. /**
  78077. * Dispose of the pipeline and stop all post processes
  78078. */
  78079. DefaultRenderingPipeline.prototype.dispose = function () {
  78080. this._disposePostProcesses(true);
  78081. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78082. this._scene.autoClear = true;
  78083. if (this._resizeObserver) {
  78084. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  78085. this._resizeObserver = null;
  78086. }
  78087. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  78088. _super.prototype.dispose.call(this);
  78089. };
  78090. /**
  78091. * Serialize the rendering pipeline (Used when exporting)
  78092. * @returns the serialized object
  78093. */
  78094. DefaultRenderingPipeline.prototype.serialize = function () {
  78095. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78096. serializationObject.customType = "DefaultRenderingPipeline";
  78097. return serializationObject;
  78098. };
  78099. /**
  78100. * Parse the serialized pipeline
  78101. * @param source Source pipeline.
  78102. * @param scene The scene to load the pipeline to.
  78103. * @param rootUrl The URL of the serialized pipeline.
  78104. * @returns An instantiated pipeline from the serialized object.
  78105. */
  78106. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78107. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  78108. };
  78109. __decorate([
  78110. BABYLON.serialize()
  78111. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  78112. __decorate([
  78113. BABYLON.serialize()
  78114. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  78115. __decorate([
  78116. BABYLON.serialize()
  78117. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  78118. __decorate([
  78119. BABYLON.serialize()
  78120. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  78121. __decorate([
  78122. BABYLON.serialize()
  78123. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  78124. __decorate([
  78125. BABYLON.serialize()
  78126. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  78127. __decorate([
  78128. BABYLON.serialize()
  78129. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  78130. __decorate([
  78131. BABYLON.serialize()
  78132. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  78133. __decorate([
  78134. BABYLON.serialize()
  78135. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  78136. __decorate([
  78137. BABYLON.serialize()
  78138. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  78139. __decorate([
  78140. BABYLON.serialize()
  78141. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  78142. __decorate([
  78143. BABYLON.serialize()
  78144. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  78145. __decorate([
  78146. BABYLON.serialize()
  78147. ], DefaultRenderingPipeline.prototype, "samples", null);
  78148. __decorate([
  78149. BABYLON.serialize()
  78150. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  78151. __decorate([
  78152. BABYLON.serialize()
  78153. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  78154. __decorate([
  78155. BABYLON.serialize()
  78156. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  78157. __decorate([
  78158. BABYLON.serialize()
  78159. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  78160. return DefaultRenderingPipeline;
  78161. }(BABYLON.PostProcessRenderPipeline));
  78162. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  78163. })(BABYLON || (BABYLON = {}));
  78164. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  78165. var BABYLON;
  78166. (function (BABYLON) {
  78167. /**
  78168. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  78169. */
  78170. var GeometryBufferRenderer = /** @class */ (function () {
  78171. /**
  78172. * Creates a new G Buffer for the scene
  78173. * @param scene The scene the buffer belongs to
  78174. * @param ratio How big is the buffer related to the main canvas.
  78175. */
  78176. function GeometryBufferRenderer(scene, ratio) {
  78177. if (ratio === void 0) { ratio = 1; }
  78178. this._enablePosition = false;
  78179. this._scene = scene;
  78180. this._ratio = ratio;
  78181. // Render target
  78182. this._createRenderTargets();
  78183. }
  78184. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  78185. /**
  78186. * Set the render list (meshes to be rendered) used in the G buffer.
  78187. */
  78188. set: function (meshes) {
  78189. this._multiRenderTarget.renderList = meshes;
  78190. },
  78191. enumerable: true,
  78192. configurable: true
  78193. });
  78194. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  78195. /**
  78196. * Gets wether or not G buffer are supported by the running hardware.
  78197. * This requires draw buffer supports
  78198. */
  78199. get: function () {
  78200. return this._multiRenderTarget.isSupported;
  78201. },
  78202. enumerable: true,
  78203. configurable: true
  78204. });
  78205. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  78206. /**
  78207. * Gets wether or not position are enabled for the G buffer.
  78208. */
  78209. get: function () {
  78210. return this._enablePosition;
  78211. },
  78212. /**
  78213. * Sets wether or not position are enabled for the G buffer.
  78214. */
  78215. set: function (enable) {
  78216. this._enablePosition = enable;
  78217. this.dispose();
  78218. this._createRenderTargets();
  78219. },
  78220. enumerable: true,
  78221. configurable: true
  78222. });
  78223. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  78224. /**
  78225. * Gets the scene associated with the buffer.
  78226. */
  78227. get: function () {
  78228. return this._scene;
  78229. },
  78230. enumerable: true,
  78231. configurable: true
  78232. });
  78233. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  78234. /**
  78235. * Gets the ratio used by the buffer during its creation.
  78236. * How big is the buffer related to the main canvas.
  78237. */
  78238. get: function () {
  78239. return this._ratio;
  78240. },
  78241. enumerable: true,
  78242. configurable: true
  78243. });
  78244. /**
  78245. * Checks wether everything is ready to render a submesh to the G buffer.
  78246. * @param subMesh the submesh to check readiness for
  78247. * @param useInstances is the mesh drawn using instance or not
  78248. * @returns true if ready otherwise false
  78249. */
  78250. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  78251. var material = subMesh.getMaterial();
  78252. if (material && material.disableDepthWrite) {
  78253. return false;
  78254. }
  78255. var defines = [];
  78256. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78257. var mesh = subMesh.getMesh();
  78258. // Alpha test
  78259. if (material && material.needAlphaTesting()) {
  78260. defines.push("#define ALPHATEST");
  78261. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78262. attribs.push(BABYLON.VertexBuffer.UVKind);
  78263. defines.push("#define UV1");
  78264. }
  78265. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78266. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78267. defines.push("#define UV2");
  78268. }
  78269. }
  78270. // Buffers
  78271. if (this._enablePosition) {
  78272. defines.push("#define POSITION");
  78273. }
  78274. // Bones
  78275. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78276. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78277. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78278. if (mesh.numBoneInfluencers > 4) {
  78279. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78280. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78281. }
  78282. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78283. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78284. }
  78285. else {
  78286. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78287. }
  78288. // Instances
  78289. if (useInstances) {
  78290. defines.push("#define INSTANCES");
  78291. attribs.push("world0");
  78292. attribs.push("world1");
  78293. attribs.push("world2");
  78294. attribs.push("world3");
  78295. }
  78296. // Get correct effect
  78297. var join = defines.join("\n");
  78298. if (this._cachedDefines !== join) {
  78299. this._cachedDefines = join;
  78300. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  78301. }
  78302. return this._effect.isReady();
  78303. };
  78304. /**
  78305. * Gets the current underlying G Buffer.
  78306. * @returns the buffer
  78307. */
  78308. GeometryBufferRenderer.prototype.getGBuffer = function () {
  78309. return this._multiRenderTarget;
  78310. };
  78311. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78312. /**
  78313. * Gets the number of samples used to render the buffer (anti aliasing).
  78314. */
  78315. get: function () {
  78316. return this._multiRenderTarget.samples;
  78317. },
  78318. /**
  78319. * Sets the number of samples used to render the buffer (anti aliasing).
  78320. */
  78321. set: function (value) {
  78322. this._multiRenderTarget.samples = value;
  78323. },
  78324. enumerable: true,
  78325. configurable: true
  78326. });
  78327. /**
  78328. * Disposes the renderer and frees up associated resources.
  78329. */
  78330. GeometryBufferRenderer.prototype.dispose = function () {
  78331. this.getGBuffer().dispose();
  78332. };
  78333. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78334. var _this = this;
  78335. var engine = this._scene.getEngine();
  78336. var count = this._enablePosition ? 3 : 2;
  78337. 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 });
  78338. if (!this.isSupported) {
  78339. return;
  78340. }
  78341. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78342. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78343. this._multiRenderTarget.refreshRate = 1;
  78344. this._multiRenderTarget.renderParticles = false;
  78345. this._multiRenderTarget.renderList = null;
  78346. // set default depth value to 1.0 (far away)
  78347. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78348. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78349. });
  78350. // Custom render function
  78351. var renderSubMesh = function (subMesh) {
  78352. var mesh = subMesh.getRenderingMesh();
  78353. var scene = _this._scene;
  78354. var engine = scene.getEngine();
  78355. var material = subMesh.getMaterial();
  78356. if (!material) {
  78357. return;
  78358. }
  78359. // Culling
  78360. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78361. // Managing instances
  78362. var batch = mesh._getInstancesRenderList(subMesh._id);
  78363. if (batch.mustReturn) {
  78364. return;
  78365. }
  78366. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78367. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78368. engine.enableEffect(_this._effect);
  78369. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78370. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78371. _this._effect.setMatrix("view", scene.getViewMatrix());
  78372. // Alpha test
  78373. if (material && material.needAlphaTesting()) {
  78374. var alphaTexture = material.getAlphaTestTexture();
  78375. if (alphaTexture) {
  78376. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78377. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78378. }
  78379. }
  78380. // Bones
  78381. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78382. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78383. }
  78384. // Draw
  78385. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78386. }
  78387. };
  78388. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78389. var index;
  78390. if (depthOnlySubMeshes.length) {
  78391. engine.setColorWrite(false);
  78392. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78393. renderSubMesh(depthOnlySubMeshes.data[index]);
  78394. }
  78395. engine.setColorWrite(true);
  78396. }
  78397. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78398. renderSubMesh(opaqueSubMeshes.data[index]);
  78399. }
  78400. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78401. renderSubMesh(alphaTestSubMeshes.data[index]);
  78402. }
  78403. };
  78404. };
  78405. return GeometryBufferRenderer;
  78406. }());
  78407. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78408. })(BABYLON || (BABYLON = {}));
  78409. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78410. var BABYLON;
  78411. (function (BABYLON) {
  78412. /**
  78413. * This groups together the common properties used for image processing either in direct forward pass
  78414. * or through post processing effect depending on the use of the image processing pipeline in your scene
  78415. * or not.
  78416. */
  78417. var ImageProcessingConfiguration = /** @class */ (function () {
  78418. function ImageProcessingConfiguration() {
  78419. /**
  78420. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  78421. */
  78422. this.colorCurves = new BABYLON.ColorCurves();
  78423. this._colorCurvesEnabled = false;
  78424. this._colorGradingEnabled = false;
  78425. this._colorGradingWithGreenDepth = true;
  78426. this._colorGradingBGR = true;
  78427. this._exposure = 1.0;
  78428. this._toneMappingEnabled = false;
  78429. this._contrast = 1.0;
  78430. /**
  78431. * Vignette stretch size.
  78432. */
  78433. this.vignetteStretch = 0;
  78434. /**
  78435. * Vignette centre X Offset.
  78436. */
  78437. this.vignetteCentreX = 0;
  78438. /**
  78439. * Vignette centre Y Offset.
  78440. */
  78441. this.vignetteCentreY = 0;
  78442. /**
  78443. * Vignette weight or intensity of the vignette effect.
  78444. */
  78445. this.vignetteWeight = 1.5;
  78446. /**
  78447. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78448. * if vignetteEnabled is set to true.
  78449. */
  78450. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  78451. /**
  78452. * Camera field of view used by the Vignette effect.
  78453. */
  78454. this.vignetteCameraFov = 0.5;
  78455. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  78456. this._vignetteEnabled = false;
  78457. this._applyByPostProcess = false;
  78458. this._isEnabled = true;
  78459. /**
  78460. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  78461. */
  78462. this.onUpdateParameters = new BABYLON.Observable();
  78463. }
  78464. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  78465. /**
  78466. * Gets wether the color curves effect is enabled.
  78467. */
  78468. get: function () {
  78469. return this._colorCurvesEnabled;
  78470. },
  78471. /**
  78472. * Sets wether the color curves effect is enabled.
  78473. */
  78474. set: function (value) {
  78475. if (this._colorCurvesEnabled === value) {
  78476. return;
  78477. }
  78478. this._colorCurvesEnabled = value;
  78479. this._updateParameters();
  78480. },
  78481. enumerable: true,
  78482. configurable: true
  78483. });
  78484. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  78485. /**
  78486. * Gets wether the color grading effect is enabled.
  78487. */
  78488. get: function () {
  78489. return this._colorGradingEnabled;
  78490. },
  78491. /**
  78492. * Sets wether the color grading effect is enabled.
  78493. */
  78494. set: function (value) {
  78495. if (this._colorGradingEnabled === value) {
  78496. return;
  78497. }
  78498. this._colorGradingEnabled = value;
  78499. this._updateParameters();
  78500. },
  78501. enumerable: true,
  78502. configurable: true
  78503. });
  78504. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  78505. /**
  78506. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  78507. */
  78508. get: function () {
  78509. return this._colorGradingWithGreenDepth;
  78510. },
  78511. /**
  78512. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  78513. */
  78514. set: function (value) {
  78515. if (this._colorGradingWithGreenDepth === value) {
  78516. return;
  78517. }
  78518. this._colorGradingWithGreenDepth = value;
  78519. this._updateParameters();
  78520. },
  78521. enumerable: true,
  78522. configurable: true
  78523. });
  78524. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  78525. /**
  78526. * Gets wether the color grading texture contains BGR values.
  78527. */
  78528. get: function () {
  78529. return this._colorGradingBGR;
  78530. },
  78531. /**
  78532. * Sets wether the color grading texture contains BGR values.
  78533. */
  78534. set: function (value) {
  78535. if (this._colorGradingBGR === value) {
  78536. return;
  78537. }
  78538. this._colorGradingBGR = value;
  78539. this._updateParameters();
  78540. },
  78541. enumerable: true,
  78542. configurable: true
  78543. });
  78544. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  78545. /**
  78546. * Gets the Exposure used in the effect.
  78547. */
  78548. get: function () {
  78549. return this._exposure;
  78550. },
  78551. /**
  78552. * Sets the Exposure used in the effect.
  78553. */
  78554. set: function (value) {
  78555. if (this._exposure === value) {
  78556. return;
  78557. }
  78558. this._exposure = value;
  78559. this._updateParameters();
  78560. },
  78561. enumerable: true,
  78562. configurable: true
  78563. });
  78564. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  78565. /**
  78566. * Gets wether the tone mapping effect is enabled.
  78567. */
  78568. get: function () {
  78569. return this._toneMappingEnabled;
  78570. },
  78571. /**
  78572. * Sets wether the tone mapping effect is enabled.
  78573. */
  78574. set: function (value) {
  78575. if (this._toneMappingEnabled === value) {
  78576. return;
  78577. }
  78578. this._toneMappingEnabled = value;
  78579. this._updateParameters();
  78580. },
  78581. enumerable: true,
  78582. configurable: true
  78583. });
  78584. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  78585. /**
  78586. * Gets the contrast used in the effect.
  78587. */
  78588. get: function () {
  78589. return this._contrast;
  78590. },
  78591. /**
  78592. * Sets the contrast used in the effect.
  78593. */
  78594. set: function (value) {
  78595. if (this._contrast === value) {
  78596. return;
  78597. }
  78598. this._contrast = value;
  78599. this._updateParameters();
  78600. },
  78601. enumerable: true,
  78602. configurable: true
  78603. });
  78604. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  78605. /**
  78606. * Gets the vignette blend mode allowing different kind of effect.
  78607. */
  78608. get: function () {
  78609. return this._vignetteBlendMode;
  78610. },
  78611. /**
  78612. * Sets the vignette blend mode allowing different kind of effect.
  78613. */
  78614. set: function (value) {
  78615. if (this._vignetteBlendMode === value) {
  78616. return;
  78617. }
  78618. this._vignetteBlendMode = value;
  78619. this._updateParameters();
  78620. },
  78621. enumerable: true,
  78622. configurable: true
  78623. });
  78624. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  78625. /**
  78626. * Gets wether the vignette effect is enabled.
  78627. */
  78628. get: function () {
  78629. return this._vignetteEnabled;
  78630. },
  78631. /**
  78632. * Sets wether the vignette effect is enabled.
  78633. */
  78634. set: function (value) {
  78635. if (this._vignetteEnabled === value) {
  78636. return;
  78637. }
  78638. this._vignetteEnabled = value;
  78639. this._updateParameters();
  78640. },
  78641. enumerable: true,
  78642. configurable: true
  78643. });
  78644. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  78645. /**
  78646. * Gets wether the image processing is applied through a post process or not.
  78647. */
  78648. get: function () {
  78649. return this._applyByPostProcess;
  78650. },
  78651. /**
  78652. * Sets wether the image processing is applied through a post process or not.
  78653. */
  78654. set: function (value) {
  78655. if (this._applyByPostProcess === value) {
  78656. return;
  78657. }
  78658. this._applyByPostProcess = value;
  78659. this._updateParameters();
  78660. },
  78661. enumerable: true,
  78662. configurable: true
  78663. });
  78664. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  78665. /**
  78666. * Gets wether the image processing is enabled or not.
  78667. */
  78668. get: function () {
  78669. return this._isEnabled;
  78670. },
  78671. /**
  78672. * Sets wether the image processing is enabled or not.
  78673. */
  78674. set: function (value) {
  78675. if (this._isEnabled === value) {
  78676. return;
  78677. }
  78678. this._isEnabled = value;
  78679. this._updateParameters();
  78680. },
  78681. enumerable: true,
  78682. configurable: true
  78683. });
  78684. /**
  78685. * Method called each time the image processing information changes requires to recompile the effect.
  78686. */
  78687. ImageProcessingConfiguration.prototype._updateParameters = function () {
  78688. this.onUpdateParameters.notifyObservers(this);
  78689. };
  78690. ImageProcessingConfiguration.prototype.getClassName = function () {
  78691. return "ImageProcessingConfiguration";
  78692. };
  78693. /**
  78694. * Prepare the list of uniforms associated with the Image Processing effects.
  78695. * @param uniformsList The list of uniforms used in the effect
  78696. * @param defines the list of defines currently in use
  78697. */
  78698. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  78699. if (defines.EXPOSURE) {
  78700. uniforms.push("exposureLinear");
  78701. }
  78702. if (defines.CONTRAST) {
  78703. uniforms.push("contrast");
  78704. }
  78705. if (defines.COLORGRADING) {
  78706. uniforms.push("colorTransformSettings");
  78707. }
  78708. if (defines.VIGNETTE) {
  78709. uniforms.push("vInverseScreenSize");
  78710. uniforms.push("vignetteSettings1");
  78711. uniforms.push("vignetteSettings2");
  78712. }
  78713. if (defines.COLORCURVES) {
  78714. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  78715. }
  78716. };
  78717. /**
  78718. * Prepare the list of samplers associated with the Image Processing effects.
  78719. * @param uniformsList The list of uniforms used in the effect
  78720. * @param defines the list of defines currently in use
  78721. */
  78722. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  78723. if (defines.COLORGRADING) {
  78724. samplersList.push("txColorTransform");
  78725. }
  78726. };
  78727. /**
  78728. * Prepare the list of defines associated to the shader.
  78729. * @param defines the list of defines to complete
  78730. */
  78731. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  78732. if (forPostProcess === void 0) { forPostProcess = false; }
  78733. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  78734. defines.VIGNETTE = false;
  78735. defines.TONEMAPPING = false;
  78736. defines.CONTRAST = false;
  78737. defines.EXPOSURE = false;
  78738. defines.COLORCURVES = false;
  78739. defines.COLORGRADING = false;
  78740. defines.COLORGRADING3D = false;
  78741. defines.IMAGEPROCESSING = false;
  78742. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  78743. return;
  78744. }
  78745. defines.VIGNETTE = this.vignetteEnabled;
  78746. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  78747. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  78748. defines.TONEMAPPING = this.toneMappingEnabled;
  78749. defines.CONTRAST = (this.contrast !== 1.0);
  78750. defines.EXPOSURE = (this.exposure !== 1.0);
  78751. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  78752. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  78753. if (defines.COLORGRADING) {
  78754. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  78755. }
  78756. else {
  78757. defines.COLORGRADING3D = false;
  78758. }
  78759. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  78760. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  78761. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  78762. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  78763. };
  78764. /**
  78765. * Returns true if all the image processing information are ready.
  78766. */
  78767. ImageProcessingConfiguration.prototype.isReady = function () {
  78768. // Color Grading texure can not be none blocking.
  78769. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  78770. };
  78771. /**
  78772. * Binds the image processing to the shader.
  78773. * @param effect The effect to bind to
  78774. */
  78775. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  78776. if (aspectRatio === void 0) { aspectRatio = 1; }
  78777. // Color Curves
  78778. if (this._colorCurvesEnabled && this.colorCurves) {
  78779. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  78780. }
  78781. // Vignette
  78782. if (this._vignetteEnabled) {
  78783. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  78784. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  78785. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  78786. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  78787. var vignetteScaleX = vignetteScaleY * aspectRatio;
  78788. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  78789. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  78790. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  78791. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  78792. var vignettePower = -2.0 * this.vignetteWeight;
  78793. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  78794. }
  78795. // Exposure
  78796. effect.setFloat("exposureLinear", this.exposure);
  78797. // Contrast
  78798. effect.setFloat("contrast", this.contrast);
  78799. // Color transform settings
  78800. if (this.colorGradingTexture) {
  78801. effect.setTexture("txColorTransform", this.colorGradingTexture);
  78802. var textureSize = this.colorGradingTexture.getSize().height;
  78803. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  78804. 0.5 / textureSize, // textureOffset
  78805. textureSize, // textureSize
  78806. this.colorGradingTexture.level // weight
  78807. );
  78808. }
  78809. };
  78810. /**
  78811. * Clones the current image processing instance.
  78812. * @return The cloned image processing
  78813. */
  78814. ImageProcessingConfiguration.prototype.clone = function () {
  78815. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  78816. };
  78817. /**
  78818. * Serializes the current image processing instance to a json representation.
  78819. * @return a JSON representation
  78820. */
  78821. ImageProcessingConfiguration.prototype.serialize = function () {
  78822. return BABYLON.SerializationHelper.Serialize(this);
  78823. };
  78824. /**
  78825. * Parses the image processing from a json representation.
  78826. * @param source the JSON source to parse
  78827. * @return The parsed image processing
  78828. */
  78829. ImageProcessingConfiguration.Parse = function (source) {
  78830. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  78831. };
  78832. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  78833. /**
  78834. * Used to apply the vignette as a mix with the pixel color.
  78835. */
  78836. get: function () {
  78837. return this._VIGNETTEMODE_MULTIPLY;
  78838. },
  78839. enumerable: true,
  78840. configurable: true
  78841. });
  78842. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  78843. /**
  78844. * Used to apply the vignette as a replacement of the pixel color.
  78845. */
  78846. get: function () {
  78847. return this._VIGNETTEMODE_OPAQUE;
  78848. },
  78849. enumerable: true,
  78850. configurable: true
  78851. });
  78852. // Static constants associated to the image processing.
  78853. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  78854. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  78855. __decorate([
  78856. BABYLON.serializeAsColorCurves()
  78857. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  78858. __decorate([
  78859. BABYLON.serialize()
  78860. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  78861. __decorate([
  78862. BABYLON.serializeAsTexture()
  78863. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  78864. __decorate([
  78865. BABYLON.serialize()
  78866. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  78867. __decorate([
  78868. BABYLON.serialize()
  78869. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  78870. __decorate([
  78871. BABYLON.serialize()
  78872. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  78873. __decorate([
  78874. BABYLON.serialize()
  78875. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  78876. __decorate([
  78877. BABYLON.serialize()
  78878. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  78879. __decorate([
  78880. BABYLON.serialize()
  78881. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  78882. __decorate([
  78883. BABYLON.serialize()
  78884. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  78885. __decorate([
  78886. BABYLON.serialize()
  78887. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  78888. __decorate([
  78889. BABYLON.serialize()
  78890. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  78891. __decorate([
  78892. BABYLON.serialize()
  78893. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  78894. __decorate([
  78895. BABYLON.serializeAsColor4()
  78896. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  78897. __decorate([
  78898. BABYLON.serialize()
  78899. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  78900. __decorate([
  78901. BABYLON.serialize()
  78902. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  78903. __decorate([
  78904. BABYLON.serialize()
  78905. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  78906. __decorate([
  78907. BABYLON.serialize()
  78908. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  78909. __decorate([
  78910. BABYLON.serialize()
  78911. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  78912. return ImageProcessingConfiguration;
  78913. }());
  78914. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  78915. })(BABYLON || (BABYLON = {}));
  78916. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  78917. var BABYLON;
  78918. (function (BABYLON) {
  78919. /**
  78920. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  78921. * It can help converting any input color in a desired output one. This can then be used to create effects
  78922. * from sepia, black and white to sixties or futuristic rendering...
  78923. *
  78924. * The only supported format is currently 3dl.
  78925. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  78926. */
  78927. var ColorGradingTexture = /** @class */ (function (_super) {
  78928. __extends(ColorGradingTexture, _super);
  78929. /**
  78930. * Instantiates a ColorGradingTexture from the following parameters.
  78931. *
  78932. * @param url The location of the color gradind data (currently only supporting 3dl)
  78933. * @param scene The scene the texture will be used in
  78934. */
  78935. function ColorGradingTexture(url, scene) {
  78936. var _this = _super.call(this, scene) || this;
  78937. if (!url) {
  78938. return _this;
  78939. }
  78940. _this._engine = scene.getEngine();
  78941. _this._textureMatrix = BABYLON.Matrix.Identity();
  78942. _this.name = url;
  78943. _this.url = url;
  78944. _this.hasAlpha = false;
  78945. _this.isCube = false;
  78946. _this.is3D = _this._engine.webGLVersion > 1;
  78947. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78948. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78949. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78950. _this.anisotropicFilteringLevel = 1;
  78951. _this._texture = _this._getFromCache(url, true);
  78952. if (!_this._texture) {
  78953. if (!scene.useDelayedTextureLoading) {
  78954. _this.loadTexture();
  78955. }
  78956. else {
  78957. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  78958. }
  78959. }
  78960. return _this;
  78961. }
  78962. /**
  78963. * Returns the texture matrix used in most of the material.
  78964. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  78965. */
  78966. ColorGradingTexture.prototype.getTextureMatrix = function () {
  78967. return this._textureMatrix;
  78968. };
  78969. /**
  78970. * Occurs when the file being loaded is a .3dl LUT file.
  78971. */
  78972. ColorGradingTexture.prototype.load3dlTexture = function () {
  78973. var engine = this._engine;
  78974. var texture;
  78975. if (engine.webGLVersion === 1) {
  78976. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78977. }
  78978. else {
  78979. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78980. }
  78981. this._texture = texture;
  78982. var callback = function (text) {
  78983. if (typeof text !== "string") {
  78984. return;
  78985. }
  78986. var data = null;
  78987. var tempData = null;
  78988. var line;
  78989. var lines = text.split('\n');
  78990. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  78991. var maxColor = 0;
  78992. for (var i = 0; i < lines.length; i++) {
  78993. line = lines[i];
  78994. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  78995. continue;
  78996. if (line.indexOf('#') === 0)
  78997. continue;
  78998. var words = line.split(" ");
  78999. if (size === 0) {
  79000. // Number of space + one
  79001. size = words.length;
  79002. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  79003. tempData = new Float32Array(size * size * size * 4);
  79004. continue;
  79005. }
  79006. if (size != 0) {
  79007. var r = Math.max(parseInt(words[0]), 0);
  79008. var g = Math.max(parseInt(words[1]), 0);
  79009. var b = Math.max(parseInt(words[2]), 0);
  79010. maxColor = Math.max(r, maxColor);
  79011. maxColor = Math.max(g, maxColor);
  79012. maxColor = Math.max(b, maxColor);
  79013. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  79014. if (tempData) {
  79015. tempData[pixelStorageIndex + 0] = r;
  79016. tempData[pixelStorageIndex + 1] = g;
  79017. tempData[pixelStorageIndex + 2] = b;
  79018. }
  79019. pixelIndexSlice++;
  79020. if (pixelIndexSlice % size == 0) {
  79021. pixelIndexH++;
  79022. pixelIndexSlice = 0;
  79023. if (pixelIndexH % size == 0) {
  79024. pixelIndexW++;
  79025. pixelIndexH = 0;
  79026. }
  79027. }
  79028. }
  79029. }
  79030. if (tempData && data) {
  79031. for (var i = 0; i < tempData.length; i++) {
  79032. if (i > 0 && (i + 1) % 4 === 0) {
  79033. data[i] = 255;
  79034. }
  79035. else {
  79036. var value = tempData[i];
  79037. data[i] = (value / maxColor * 255);
  79038. }
  79039. }
  79040. }
  79041. if (texture.is3D) {
  79042. texture.updateSize(size, size, size);
  79043. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79044. }
  79045. else {
  79046. texture.updateSize(size * size, size);
  79047. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79048. }
  79049. };
  79050. var scene = this.getScene();
  79051. if (scene) {
  79052. scene._loadFile(this.url, callback);
  79053. }
  79054. else {
  79055. this._engine._loadFile(this.url, callback);
  79056. }
  79057. return this._texture;
  79058. };
  79059. /**
  79060. * Starts the loading process of the texture.
  79061. */
  79062. ColorGradingTexture.prototype.loadTexture = function () {
  79063. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  79064. this.load3dlTexture();
  79065. }
  79066. };
  79067. /**
  79068. * Clones the color gradind texture.
  79069. */
  79070. ColorGradingTexture.prototype.clone = function () {
  79071. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  79072. // Base texture
  79073. newTexture.level = this.level;
  79074. return newTexture;
  79075. };
  79076. /**
  79077. * Called during delayed load for textures.
  79078. */
  79079. ColorGradingTexture.prototype.delayLoad = function () {
  79080. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79081. return;
  79082. }
  79083. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79084. this._texture = this._getFromCache(this.url, true);
  79085. if (!this._texture) {
  79086. this.loadTexture();
  79087. }
  79088. };
  79089. /**
  79090. * Parses a color grading texture serialized by Babylon.
  79091. * @param parsedTexture The texture information being parsedTexture
  79092. * @param scene The scene to load the texture in
  79093. * @param rootUrl The root url of the data assets to load
  79094. * @return A color gradind texture
  79095. */
  79096. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79097. var texture = null;
  79098. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79099. texture = new ColorGradingTexture(parsedTexture.name, scene);
  79100. texture.name = parsedTexture.name;
  79101. texture.level = parsedTexture.level;
  79102. }
  79103. return texture;
  79104. };
  79105. /**
  79106. * Serializes the LUT texture to json format.
  79107. */
  79108. ColorGradingTexture.prototype.serialize = function () {
  79109. if (!this.name) {
  79110. return null;
  79111. }
  79112. var serializationObject = {};
  79113. serializationObject.name = this.name;
  79114. serializationObject.level = this.level;
  79115. serializationObject.customType = "BABYLON.ColorGradingTexture";
  79116. return serializationObject;
  79117. };
  79118. /**
  79119. * Empty line regex stored for GC.
  79120. */
  79121. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  79122. return ColorGradingTexture;
  79123. }(BABYLON.BaseTexture));
  79124. BABYLON.ColorGradingTexture = ColorGradingTexture;
  79125. })(BABYLON || (BABYLON = {}));
  79126. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  79127. var BABYLON;
  79128. (function (BABYLON) {
  79129. /**
  79130. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  79131. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  79132. * 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;
  79133. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  79134. */
  79135. var ColorCurves = /** @class */ (function () {
  79136. function ColorCurves() {
  79137. this._dirty = true;
  79138. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  79139. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  79140. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79141. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  79142. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79143. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  79144. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  79145. this._globalHue = 30;
  79146. this._globalDensity = 0;
  79147. this._globalSaturation = 0;
  79148. this._globalExposure = 0;
  79149. this._highlightsHue = 30;
  79150. this._highlightsDensity = 0;
  79151. this._highlightsSaturation = 0;
  79152. this._highlightsExposure = 0;
  79153. this._midtonesHue = 30;
  79154. this._midtonesDensity = 0;
  79155. this._midtonesSaturation = 0;
  79156. this._midtonesExposure = 0;
  79157. this._shadowsHue = 30;
  79158. this._shadowsDensity = 0;
  79159. this._shadowsSaturation = 0;
  79160. this._shadowsExposure = 0;
  79161. }
  79162. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  79163. /**
  79164. * Gets the global Hue value.
  79165. * 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).
  79166. */
  79167. get: function () {
  79168. return this._globalHue;
  79169. },
  79170. /**
  79171. * Sets the global Hue value.
  79172. * 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).
  79173. */
  79174. set: function (value) {
  79175. this._globalHue = value;
  79176. this._dirty = true;
  79177. },
  79178. enumerable: true,
  79179. configurable: true
  79180. });
  79181. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  79182. /**
  79183. * Gets the global Density value.
  79184. * 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.
  79185. * Values less than zero provide a filter of opposite hue.
  79186. */
  79187. get: function () {
  79188. return this._globalDensity;
  79189. },
  79190. /**
  79191. * Sets the global Density value.
  79192. * 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.
  79193. * Values less than zero provide a filter of opposite hue.
  79194. */
  79195. set: function (value) {
  79196. this._globalDensity = value;
  79197. this._dirty = true;
  79198. },
  79199. enumerable: true,
  79200. configurable: true
  79201. });
  79202. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  79203. /**
  79204. * Gets the global Saturation value.
  79205. * 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.
  79206. */
  79207. get: function () {
  79208. return this._globalSaturation;
  79209. },
  79210. /**
  79211. * Sets the global Saturation value.
  79212. * 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.
  79213. */
  79214. set: function (value) {
  79215. this._globalSaturation = value;
  79216. this._dirty = true;
  79217. },
  79218. enumerable: true,
  79219. configurable: true
  79220. });
  79221. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  79222. /**
  79223. * Gets the global Exposure value.
  79224. * 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.
  79225. */
  79226. get: function () {
  79227. return this._globalExposure;
  79228. },
  79229. /**
  79230. * Sets the global Exposure value.
  79231. * 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.
  79232. */
  79233. set: function (value) {
  79234. this._globalExposure = value;
  79235. this._dirty = true;
  79236. },
  79237. enumerable: true,
  79238. configurable: true
  79239. });
  79240. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  79241. /**
  79242. * Gets the highlights Hue value.
  79243. * 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).
  79244. */
  79245. get: function () {
  79246. return this._highlightsHue;
  79247. },
  79248. /**
  79249. * Sets the highlights Hue value.
  79250. * 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).
  79251. */
  79252. set: function (value) {
  79253. this._highlightsHue = value;
  79254. this._dirty = true;
  79255. },
  79256. enumerable: true,
  79257. configurable: true
  79258. });
  79259. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  79260. /**
  79261. * Gets the highlights Density value.
  79262. * 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.
  79263. * Values less than zero provide a filter of opposite hue.
  79264. */
  79265. get: function () {
  79266. return this._highlightsDensity;
  79267. },
  79268. /**
  79269. * Sets the highlights Density value.
  79270. * 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.
  79271. * Values less than zero provide a filter of opposite hue.
  79272. */
  79273. set: function (value) {
  79274. this._highlightsDensity = value;
  79275. this._dirty = true;
  79276. },
  79277. enumerable: true,
  79278. configurable: true
  79279. });
  79280. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  79281. /**
  79282. * Gets the highlights Saturation value.
  79283. * 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.
  79284. */
  79285. get: function () {
  79286. return this._highlightsSaturation;
  79287. },
  79288. /**
  79289. * Sets the highlights Saturation value.
  79290. * 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.
  79291. */
  79292. set: function (value) {
  79293. this._highlightsSaturation = value;
  79294. this._dirty = true;
  79295. },
  79296. enumerable: true,
  79297. configurable: true
  79298. });
  79299. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  79300. /**
  79301. * Gets the highlights Exposure value.
  79302. * 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.
  79303. */
  79304. get: function () {
  79305. return this._highlightsExposure;
  79306. },
  79307. /**
  79308. * Sets the highlights Exposure value.
  79309. * 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.
  79310. */
  79311. set: function (value) {
  79312. this._highlightsExposure = value;
  79313. this._dirty = true;
  79314. },
  79315. enumerable: true,
  79316. configurable: true
  79317. });
  79318. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  79319. /**
  79320. * Gets the midtones Hue value.
  79321. * 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).
  79322. */
  79323. get: function () {
  79324. return this._midtonesHue;
  79325. },
  79326. /**
  79327. * Sets the midtones Hue value.
  79328. * 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).
  79329. */
  79330. set: function (value) {
  79331. this._midtonesHue = value;
  79332. this._dirty = true;
  79333. },
  79334. enumerable: true,
  79335. configurable: true
  79336. });
  79337. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  79338. /**
  79339. * Gets the midtones Density value.
  79340. * 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.
  79341. * Values less than zero provide a filter of opposite hue.
  79342. */
  79343. get: function () {
  79344. return this._midtonesDensity;
  79345. },
  79346. /**
  79347. * Sets the midtones Density value.
  79348. * 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.
  79349. * Values less than zero provide a filter of opposite hue.
  79350. */
  79351. set: function (value) {
  79352. this._midtonesDensity = value;
  79353. this._dirty = true;
  79354. },
  79355. enumerable: true,
  79356. configurable: true
  79357. });
  79358. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  79359. /**
  79360. * Gets the midtones Saturation value.
  79361. * 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.
  79362. */
  79363. get: function () {
  79364. return this._midtonesSaturation;
  79365. },
  79366. /**
  79367. * Sets the midtones Saturation value.
  79368. * 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.
  79369. */
  79370. set: function (value) {
  79371. this._midtonesSaturation = value;
  79372. this._dirty = true;
  79373. },
  79374. enumerable: true,
  79375. configurable: true
  79376. });
  79377. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  79378. /**
  79379. * Gets the midtones Exposure value.
  79380. * 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.
  79381. */
  79382. get: function () {
  79383. return this._midtonesExposure;
  79384. },
  79385. /**
  79386. * Sets the midtones Exposure value.
  79387. * 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.
  79388. */
  79389. set: function (value) {
  79390. this._midtonesExposure = value;
  79391. this._dirty = true;
  79392. },
  79393. enumerable: true,
  79394. configurable: true
  79395. });
  79396. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  79397. /**
  79398. * Gets the shadows Hue value.
  79399. * 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).
  79400. */
  79401. get: function () {
  79402. return this._shadowsHue;
  79403. },
  79404. /**
  79405. * Sets the shadows Hue value.
  79406. * 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).
  79407. */
  79408. set: function (value) {
  79409. this._shadowsHue = value;
  79410. this._dirty = true;
  79411. },
  79412. enumerable: true,
  79413. configurable: true
  79414. });
  79415. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  79416. /**
  79417. * Gets the shadows Density value.
  79418. * 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.
  79419. * Values less than zero provide a filter of opposite hue.
  79420. */
  79421. get: function () {
  79422. return this._shadowsDensity;
  79423. },
  79424. /**
  79425. * Sets the shadows Density value.
  79426. * 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.
  79427. * Values less than zero provide a filter of opposite hue.
  79428. */
  79429. set: function (value) {
  79430. this._shadowsDensity = value;
  79431. this._dirty = true;
  79432. },
  79433. enumerable: true,
  79434. configurable: true
  79435. });
  79436. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  79437. /**
  79438. * Gets the shadows Saturation value.
  79439. * 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.
  79440. */
  79441. get: function () {
  79442. return this._shadowsSaturation;
  79443. },
  79444. /**
  79445. * Sets the shadows Saturation value.
  79446. * 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.
  79447. */
  79448. set: function (value) {
  79449. this._shadowsSaturation = value;
  79450. this._dirty = true;
  79451. },
  79452. enumerable: true,
  79453. configurable: true
  79454. });
  79455. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  79456. /**
  79457. * Gets the shadows Exposure value.
  79458. * 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.
  79459. */
  79460. get: function () {
  79461. return this._shadowsExposure;
  79462. },
  79463. /**
  79464. * Sets the shadows Exposure value.
  79465. * 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.
  79466. */
  79467. set: function (value) {
  79468. this._shadowsExposure = value;
  79469. this._dirty = true;
  79470. },
  79471. enumerable: true,
  79472. configurable: true
  79473. });
  79474. ColorCurves.prototype.getClassName = function () {
  79475. return "ColorCurves";
  79476. };
  79477. /**
  79478. * Binds the color curves to the shader.
  79479. * @param colorCurves The color curve to bind
  79480. * @param effect The effect to bind to
  79481. */
  79482. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  79483. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  79484. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  79485. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  79486. if (colorCurves._dirty) {
  79487. colorCurves._dirty = false;
  79488. // Fill in global info.
  79489. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  79490. // Compute highlights info.
  79491. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  79492. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  79493. // Compute midtones info.
  79494. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  79495. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  79496. // Compute shadows info.
  79497. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  79498. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  79499. // Compute deltas (neutral is midtones).
  79500. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  79501. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  79502. }
  79503. if (effect) {
  79504. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  79505. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  79506. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  79507. }
  79508. };
  79509. /**
  79510. * Prepare the list of uniforms associated with the ColorCurves effects.
  79511. * @param uniformsList The list of uniforms used in the effect
  79512. */
  79513. ColorCurves.PrepareUniforms = function (uniformsList) {
  79514. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  79515. };
  79516. /**
  79517. * Returns color grading data based on a hue, density, saturation and exposure value.
  79518. * @param filterHue The hue of the color filter.
  79519. * @param filterDensity The density of the color filter.
  79520. * @param saturation The saturation.
  79521. * @param exposure The exposure.
  79522. * @param result The result data container.
  79523. */
  79524. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  79525. if (hue == null) {
  79526. return;
  79527. }
  79528. hue = ColorCurves.clamp(hue, 0, 360);
  79529. density = ColorCurves.clamp(density, -100, 100);
  79530. saturation = ColorCurves.clamp(saturation, -100, 100);
  79531. exposure = ColorCurves.clamp(exposure, -100, 100);
  79532. // Remap the slider/config filter density with non-linear mapping and also scale by half
  79533. // so that the maximum filter density is only 50% control. This provides fine control
  79534. // for small values and reasonable range.
  79535. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  79536. density *= 0.5;
  79537. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  79538. if (density < 0) {
  79539. density *= -1;
  79540. hue = (hue + 180) % 360;
  79541. }
  79542. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  79543. result.scaleToRef(2, result);
  79544. result.a = 1 + 0.01 * saturation;
  79545. };
  79546. /**
  79547. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  79548. * @param value The input slider value in range [-100,100].
  79549. * @returns Adjusted value.
  79550. */
  79551. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  79552. value /= 100;
  79553. var x = Math.abs(value);
  79554. x = Math.pow(x, 2);
  79555. if (value < 0) {
  79556. x *= -1;
  79557. }
  79558. x *= 100;
  79559. return x;
  79560. };
  79561. /**
  79562. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  79563. * @param hue The hue (H) input.
  79564. * @param saturation The saturation (S) input.
  79565. * @param brightness The brightness (B) input.
  79566. * @result An RGBA color represented as Vector4.
  79567. */
  79568. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  79569. var h = ColorCurves.clamp(hue, 0, 360);
  79570. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  79571. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  79572. if (s === 0) {
  79573. result.r = v;
  79574. result.g = v;
  79575. result.b = v;
  79576. }
  79577. else {
  79578. // sector 0 to 5
  79579. h /= 60;
  79580. var i = Math.floor(h);
  79581. // fractional part of h
  79582. var f = h - i;
  79583. var p = v * (1 - s);
  79584. var q = v * (1 - s * f);
  79585. var t = v * (1 - s * (1 - f));
  79586. switch (i) {
  79587. case 0:
  79588. result.r = v;
  79589. result.g = t;
  79590. result.b = p;
  79591. break;
  79592. case 1:
  79593. result.r = q;
  79594. result.g = v;
  79595. result.b = p;
  79596. break;
  79597. case 2:
  79598. result.r = p;
  79599. result.g = v;
  79600. result.b = t;
  79601. break;
  79602. case 3:
  79603. result.r = p;
  79604. result.g = q;
  79605. result.b = v;
  79606. break;
  79607. case 4:
  79608. result.r = t;
  79609. result.g = p;
  79610. result.b = v;
  79611. break;
  79612. default: // case 5:
  79613. result.r = v;
  79614. result.g = p;
  79615. result.b = q;
  79616. break;
  79617. }
  79618. }
  79619. result.a = 1;
  79620. };
  79621. /**
  79622. * Returns a value clamped between min and max
  79623. * @param value The value to clamp
  79624. * @param min The minimum of value
  79625. * @param max The maximum of value
  79626. * @returns The clamped value.
  79627. */
  79628. ColorCurves.clamp = function (value, min, max) {
  79629. return Math.min(Math.max(value, min), max);
  79630. };
  79631. /**
  79632. * Clones the current color curve instance.
  79633. * @return The cloned curves
  79634. */
  79635. ColorCurves.prototype.clone = function () {
  79636. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  79637. };
  79638. /**
  79639. * Serializes the current color curve instance to a json representation.
  79640. * @return a JSON representation
  79641. */
  79642. ColorCurves.prototype.serialize = function () {
  79643. return BABYLON.SerializationHelper.Serialize(this);
  79644. };
  79645. /**
  79646. * Parses the color curve from a json representation.
  79647. * @param source the JSON source to parse
  79648. * @return The parsed curves
  79649. */
  79650. ColorCurves.Parse = function (source) {
  79651. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  79652. };
  79653. __decorate([
  79654. BABYLON.serialize()
  79655. ], ColorCurves.prototype, "_globalHue", void 0);
  79656. __decorate([
  79657. BABYLON.serialize()
  79658. ], ColorCurves.prototype, "_globalDensity", void 0);
  79659. __decorate([
  79660. BABYLON.serialize()
  79661. ], ColorCurves.prototype, "_globalSaturation", void 0);
  79662. __decorate([
  79663. BABYLON.serialize()
  79664. ], ColorCurves.prototype, "_globalExposure", void 0);
  79665. __decorate([
  79666. BABYLON.serialize()
  79667. ], ColorCurves.prototype, "_highlightsHue", void 0);
  79668. __decorate([
  79669. BABYLON.serialize()
  79670. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  79671. __decorate([
  79672. BABYLON.serialize()
  79673. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  79674. __decorate([
  79675. BABYLON.serialize()
  79676. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  79677. __decorate([
  79678. BABYLON.serialize()
  79679. ], ColorCurves.prototype, "_midtonesHue", void 0);
  79680. __decorate([
  79681. BABYLON.serialize()
  79682. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  79683. __decorate([
  79684. BABYLON.serialize()
  79685. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  79686. __decorate([
  79687. BABYLON.serialize()
  79688. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  79689. return ColorCurves;
  79690. }());
  79691. BABYLON.ColorCurves = ColorCurves;
  79692. })(BABYLON || (BABYLON = {}));
  79693. //# sourceMappingURL=babylon.colorCurves.js.map
  79694. var BABYLON;
  79695. (function (BABYLON) {
  79696. var RefractionPostProcess = /** @class */ (function (_super) {
  79697. __extends(RefractionPostProcess, _super);
  79698. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  79699. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  79700. _this.color = color;
  79701. _this.depth = depth;
  79702. _this.colorLevel = colorLevel;
  79703. _this._ownRefractionTexture = true;
  79704. _this.onActivateObservable.add(function (cam) {
  79705. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  79706. });
  79707. _this.onApplyObservable.add(function (effect) {
  79708. effect.setColor3("baseColor", _this.color);
  79709. effect.setFloat("depth", _this.depth);
  79710. effect.setFloat("colorLevel", _this.colorLevel);
  79711. effect.setTexture("refractionSampler", _this._refTexture);
  79712. });
  79713. return _this;
  79714. }
  79715. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  79716. /**
  79717. * Gets or sets the refraction texture
  79718. * Please note that you are responsible for disposing the texture if you set it manually
  79719. */
  79720. get: function () {
  79721. return this._refTexture;
  79722. },
  79723. set: function (value) {
  79724. if (this._refTexture && this._ownRefractionTexture) {
  79725. this._refTexture.dispose();
  79726. }
  79727. this._refTexture = value;
  79728. this._ownRefractionTexture = false;
  79729. },
  79730. enumerable: true,
  79731. configurable: true
  79732. });
  79733. // Methods
  79734. RefractionPostProcess.prototype.dispose = function (camera) {
  79735. if (this._refTexture && this._ownRefractionTexture) {
  79736. this._refTexture.dispose();
  79737. this._refTexture = null;
  79738. }
  79739. _super.prototype.dispose.call(this, camera);
  79740. };
  79741. return RefractionPostProcess;
  79742. }(BABYLON.PostProcess));
  79743. BABYLON.RefractionPostProcess = RefractionPostProcess;
  79744. })(BABYLON || (BABYLON = {}));
  79745. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  79746. var BABYLON;
  79747. (function (BABYLON) {
  79748. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  79749. __extends(BlackAndWhitePostProcess, _super);
  79750. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  79751. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  79752. _this.degree = 1;
  79753. _this.onApplyObservable.add(function (effect) {
  79754. effect.setFloat("degree", _this.degree);
  79755. });
  79756. return _this;
  79757. }
  79758. return BlackAndWhitePostProcess;
  79759. }(BABYLON.PostProcess));
  79760. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  79761. })(BABYLON || (BABYLON = {}));
  79762. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  79763. var BABYLON;
  79764. (function (BABYLON) {
  79765. /**
  79766. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  79767. * input texture to perform effects such as edge detection or sharpening
  79768. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  79769. */
  79770. var ConvolutionPostProcess = /** @class */ (function (_super) {
  79771. __extends(ConvolutionPostProcess, _super);
  79772. /**
  79773. * Creates a new instance ConvolutionPostProcess
  79774. * @param name The name of the effect.
  79775. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  79776. * @param options The required width/height ratio to downsize to before computing the render pass.
  79777. * @param camera The camera to apply the render pass to.
  79778. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79779. * @param engine The engine which the post process will be applied. (default: current engine)
  79780. * @param reusable If the post process can be reused on the same frame. (default: false)
  79781. * @param textureType Type of textures used when performing the post process. (default: 0)
  79782. */
  79783. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  79784. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79785. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79786. _this.kernel = kernel;
  79787. _this.onApply = function (effect) {
  79788. effect.setFloat2("screenSize", _this.width, _this.height);
  79789. effect.setArray("kernel", _this.kernel);
  79790. };
  79791. return _this;
  79792. }
  79793. // Statics
  79794. /**
  79795. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79796. */
  79797. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  79798. /**
  79799. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79800. */
  79801. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  79802. /**
  79803. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79804. */
  79805. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  79806. /**
  79807. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79808. */
  79809. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  79810. /**
  79811. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79812. */
  79813. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  79814. /**
  79815. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79816. */
  79817. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  79818. return ConvolutionPostProcess;
  79819. }(BABYLON.PostProcess));
  79820. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  79821. })(BABYLON || (BABYLON = {}));
  79822. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  79823. var BABYLON;
  79824. (function (BABYLON) {
  79825. var FilterPostProcess = /** @class */ (function (_super) {
  79826. __extends(FilterPostProcess, _super);
  79827. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  79828. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  79829. _this.kernelMatrix = kernelMatrix;
  79830. _this.onApply = function (effect) {
  79831. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  79832. };
  79833. return _this;
  79834. }
  79835. return FilterPostProcess;
  79836. }(BABYLON.PostProcess));
  79837. BABYLON.FilterPostProcess = FilterPostProcess;
  79838. })(BABYLON || (BABYLON = {}));
  79839. //# sourceMappingURL=babylon.filterPostProcess.js.map
  79840. var BABYLON;
  79841. (function (BABYLON) {
  79842. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  79843. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  79844. __extends(VolumetricLightScatteringPostProcess, _super);
  79845. /**
  79846. * @constructor
  79847. * @param {string} name - The post-process name
  79848. * @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)
  79849. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  79850. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  79851. * @param {number} samples - The post-process quality, default 100
  79852. * @param {number} samplingMode - The post-process filtering mode
  79853. * @param {BABYLON.Engine} engine - The babylon engine
  79854. * @param {boolean} reusable - If the post-process is reusable
  79855. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  79856. */
  79857. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  79858. if (samples === void 0) { samples = 100; }
  79859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79860. 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;
  79861. _this._screenCoordinates = BABYLON.Vector2.Zero();
  79862. /**
  79863. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  79864. */
  79865. _this.customMeshPosition = BABYLON.Vector3.Zero();
  79866. /**
  79867. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  79868. */
  79869. _this.useCustomMeshPosition = false;
  79870. /**
  79871. * If the post-process should inverse the light scattering direction
  79872. */
  79873. _this.invert = true;
  79874. /**
  79875. * Array containing the excluded meshes not rendered in the internal pass
  79876. */
  79877. _this.excludedMeshes = new Array();
  79878. /**
  79879. * Controls the overall intensity of the post-process
  79880. */
  79881. _this.exposure = 0.3;
  79882. /**
  79883. * Dissipates each sample's contribution in range [0, 1]
  79884. */
  79885. _this.decay = 0.96815;
  79886. /**
  79887. * Controls the overall intensity of each sample
  79888. */
  79889. _this.weight = 0.58767;
  79890. /**
  79891. * Controls the density of each sample
  79892. */
  79893. _this.density = 0.926;
  79894. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  79895. engine = scene.getEngine();
  79896. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  79897. // Configure mesh
  79898. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  79899. // Configure
  79900. _this._createPass(scene, ratio.passRatio || ratio);
  79901. _this.onActivate = function (camera) {
  79902. if (!_this.isSupported) {
  79903. _this.dispose(camera);
  79904. }
  79905. _this.onActivate = null;
  79906. };
  79907. _this.onApplyObservable.add(function (effect) {
  79908. _this._updateMeshScreenCoordinates(scene);
  79909. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  79910. effect.setFloat("exposure", _this.exposure);
  79911. effect.setFloat("decay", _this.decay);
  79912. effect.setFloat("weight", _this.weight);
  79913. effect.setFloat("density", _this.density);
  79914. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  79915. });
  79916. return _this;
  79917. }
  79918. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  79919. get: function () {
  79920. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  79921. return false;
  79922. },
  79923. set: function (useDiffuseColor) {
  79924. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  79925. },
  79926. enumerable: true,
  79927. configurable: true
  79928. });
  79929. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  79930. return "VolumetricLightScatteringPostProcess";
  79931. };
  79932. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  79933. var mesh = subMesh.getMesh();
  79934. // Render this.mesh as default
  79935. if (mesh === this.mesh && mesh.material) {
  79936. return mesh.material.isReady(mesh);
  79937. }
  79938. var defines = [];
  79939. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79940. var material = subMesh.getMaterial();
  79941. // Alpha test
  79942. if (material) {
  79943. if (material.needAlphaTesting()) {
  79944. defines.push("#define ALPHATEST");
  79945. }
  79946. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79947. attribs.push(BABYLON.VertexBuffer.UVKind);
  79948. defines.push("#define UV1");
  79949. }
  79950. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79951. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79952. defines.push("#define UV2");
  79953. }
  79954. }
  79955. // Bones
  79956. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79957. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79958. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79959. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79960. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  79961. }
  79962. else {
  79963. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79964. }
  79965. // Instances
  79966. if (useInstances) {
  79967. defines.push("#define INSTANCES");
  79968. attribs.push("world0");
  79969. attribs.push("world1");
  79970. attribs.push("world2");
  79971. attribs.push("world3");
  79972. }
  79973. // Get correct effect
  79974. var join = defines.join("\n");
  79975. if (this._cachedDefines !== join) {
  79976. this._cachedDefines = join;
  79977. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  79978. }
  79979. return this._volumetricLightScatteringPass.isReady();
  79980. };
  79981. /**
  79982. * Sets the new light position for light scattering effect
  79983. * @param {BABYLON.Vector3} The new custom light position
  79984. */
  79985. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  79986. this.customMeshPosition = position;
  79987. };
  79988. /**
  79989. * Returns the light position for light scattering effect
  79990. * @return {BABYLON.Vector3} The custom light position
  79991. */
  79992. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  79993. return this.customMeshPosition;
  79994. };
  79995. /**
  79996. * Disposes the internal assets and detaches the post-process from the camera
  79997. */
  79998. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  79999. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  80000. if (rttIndex !== -1) {
  80001. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  80002. }
  80003. this._volumetricLightScatteringRTT.dispose();
  80004. _super.prototype.dispose.call(this, camera);
  80005. };
  80006. /**
  80007. * Returns the render target texture used by the post-process
  80008. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  80009. */
  80010. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  80011. return this._volumetricLightScatteringRTT;
  80012. };
  80013. // Private methods
  80014. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  80015. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  80016. return true;
  80017. }
  80018. return false;
  80019. };
  80020. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  80021. var _this = this;
  80022. var engine = scene.getEngine();
  80023. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80024. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80025. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80026. this._volumetricLightScatteringRTT.renderList = null;
  80027. this._volumetricLightScatteringRTT.renderParticles = false;
  80028. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  80029. var camera = this.getCamera();
  80030. if (camera) {
  80031. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80032. }
  80033. else {
  80034. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80035. }
  80036. // Custom render function for submeshes
  80037. var renderSubMesh = function (subMesh) {
  80038. var mesh = subMesh.getRenderingMesh();
  80039. if (_this._meshExcluded(mesh)) {
  80040. return;
  80041. }
  80042. var material = subMesh.getMaterial();
  80043. if (!material) {
  80044. return;
  80045. }
  80046. var scene = mesh.getScene();
  80047. var engine = scene.getEngine();
  80048. // Culling
  80049. engine.setState(material.backFaceCulling);
  80050. // Managing instances
  80051. var batch = mesh._getInstancesRenderList(subMesh._id);
  80052. if (batch.mustReturn) {
  80053. return;
  80054. }
  80055. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80056. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  80057. var effect = _this._volumetricLightScatteringPass;
  80058. if (mesh === _this.mesh) {
  80059. if (subMesh.effect) {
  80060. effect = subMesh.effect;
  80061. }
  80062. else {
  80063. effect = material.getEffect();
  80064. }
  80065. }
  80066. engine.enableEffect(effect);
  80067. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  80068. if (mesh === _this.mesh) {
  80069. material.bind(mesh.getWorldMatrix(), mesh);
  80070. }
  80071. else {
  80072. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  80073. // Alpha test
  80074. if (material && material.needAlphaTesting()) {
  80075. var alphaTexture = material.getAlphaTestTexture();
  80076. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  80077. if (alphaTexture) {
  80078. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80079. }
  80080. }
  80081. // Bones
  80082. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80083. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80084. }
  80085. }
  80086. // Draw
  80087. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  80088. }
  80089. };
  80090. // Render target texture callbacks
  80091. var savedSceneClearColor;
  80092. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  80093. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  80094. savedSceneClearColor = scene.clearColor;
  80095. scene.clearColor = sceneClearColor;
  80096. });
  80097. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  80098. scene.clearColor = savedSceneClearColor;
  80099. });
  80100. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80101. var engine = scene.getEngine();
  80102. var index;
  80103. if (depthOnlySubMeshes.length) {
  80104. engine.setColorWrite(false);
  80105. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80106. renderSubMesh(depthOnlySubMeshes.data[index]);
  80107. }
  80108. engine.setColorWrite(true);
  80109. }
  80110. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80111. renderSubMesh(opaqueSubMeshes.data[index]);
  80112. }
  80113. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80114. renderSubMesh(alphaTestSubMeshes.data[index]);
  80115. }
  80116. if (transparentSubMeshes.length) {
  80117. // Sort sub meshes
  80118. for (index = 0; index < transparentSubMeshes.length; index++) {
  80119. var submesh = transparentSubMeshes.data[index];
  80120. var boundingInfo = submesh.getBoundingInfo();
  80121. if (boundingInfo && scene.activeCamera) {
  80122. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  80123. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  80124. }
  80125. }
  80126. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  80127. sortedArray.sort(function (a, b) {
  80128. // Alpha index first
  80129. if (a._alphaIndex > b._alphaIndex) {
  80130. return 1;
  80131. }
  80132. if (a._alphaIndex < b._alphaIndex) {
  80133. return -1;
  80134. }
  80135. // Then distance to camera
  80136. if (a._distanceToCamera < b._distanceToCamera) {
  80137. return 1;
  80138. }
  80139. if (a._distanceToCamera > b._distanceToCamera) {
  80140. return -1;
  80141. }
  80142. return 0;
  80143. });
  80144. // Render sub meshes
  80145. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  80146. for (index = 0; index < sortedArray.length; index++) {
  80147. renderSubMesh(sortedArray[index]);
  80148. }
  80149. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80150. }
  80151. };
  80152. };
  80153. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  80154. var transform = scene.getTransformMatrix();
  80155. var meshPosition;
  80156. if (this.useCustomMeshPosition) {
  80157. meshPosition = this.customMeshPosition;
  80158. }
  80159. else if (this.attachedNode) {
  80160. meshPosition = this.attachedNode.position;
  80161. }
  80162. else {
  80163. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  80164. }
  80165. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  80166. this._screenCoordinates.x = pos.x / this._viewPort.width;
  80167. this._screenCoordinates.y = pos.y / this._viewPort.height;
  80168. if (this.invert)
  80169. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  80170. };
  80171. // Static methods
  80172. /**
  80173. * Creates a default mesh for the Volumeric Light Scattering post-process
  80174. * @param {string} The mesh name
  80175. * @param {BABYLON.Scene} The scene where to create the mesh
  80176. * @return {BABYLON.Mesh} the default mesh
  80177. */
  80178. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  80179. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  80180. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  80181. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  80182. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  80183. mesh.material = material;
  80184. return mesh;
  80185. };
  80186. __decorate([
  80187. BABYLON.serializeAsVector3()
  80188. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  80189. __decorate([
  80190. BABYLON.serialize()
  80191. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  80192. __decorate([
  80193. BABYLON.serialize()
  80194. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  80195. __decorate([
  80196. BABYLON.serializeAsMeshReference()
  80197. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  80198. __decorate([
  80199. BABYLON.serialize()
  80200. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  80201. __decorate([
  80202. BABYLON.serialize()
  80203. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  80204. __decorate([
  80205. BABYLON.serialize()
  80206. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  80207. __decorate([
  80208. BABYLON.serialize()
  80209. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  80210. __decorate([
  80211. BABYLON.serialize()
  80212. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  80213. return VolumetricLightScatteringPostProcess;
  80214. }(BABYLON.PostProcess));
  80215. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  80216. })(BABYLON || (BABYLON = {}));
  80217. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  80218. //
  80219. // This post-process allows the modification of rendered colors by using
  80220. // a 'look-up table' (LUT). This effect is also called Color Grading.
  80221. //
  80222. // The object needs to be provided an url to a texture containing the color
  80223. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  80224. // Use an image editing software to tweak the LUT to match your needs.
  80225. //
  80226. // For an example of a color LUT, see here:
  80227. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  80228. // For explanations on color grading, see here:
  80229. // http://udn.epicgames.com/Three/ColorGrading.html
  80230. //
  80231. var BABYLON;
  80232. (function (BABYLON) {
  80233. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  80234. __extends(ColorCorrectionPostProcess, _super);
  80235. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  80236. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  80237. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80238. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  80239. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80240. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80241. _this.onApply = function (effect) {
  80242. effect.setTexture("colorTable", _this._colorTableTexture);
  80243. };
  80244. return _this;
  80245. }
  80246. return ColorCorrectionPostProcess;
  80247. }(BABYLON.PostProcess));
  80248. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  80249. })(BABYLON || (BABYLON = {}));
  80250. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  80251. var BABYLON;
  80252. (function (BABYLON) {
  80253. /** Defines operator used for tonemapping */
  80254. var TonemappingOperator;
  80255. (function (TonemappingOperator) {
  80256. /** Hable */
  80257. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  80258. /** Reinhard */
  80259. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  80260. /** HejiDawson */
  80261. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  80262. /** Photographic */
  80263. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  80264. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  80265. ;
  80266. /**
  80267. * Defines a post process to apply tone mapping
  80268. */
  80269. var TonemapPostProcess = /** @class */ (function (_super) {
  80270. __extends(TonemapPostProcess, _super);
  80271. /**
  80272. * Creates a new TonemapPostProcess
  80273. * @param name defines the name of the postprocess
  80274. * @param _operator defines the operator to use
  80275. * @param exposureAdjustment defines the required exposure adjustement
  80276. * @param camera defines the camera to use (can be null)
  80277. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  80278. * @param engine defines the hosting engine (can be ignore if camera is set)
  80279. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  80280. */
  80281. function TonemapPostProcess(name, _operator,
  80282. /** Defines the required exposure adjustement */
  80283. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  80284. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80285. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80286. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  80287. _this._operator = _operator;
  80288. _this.exposureAdjustment = exposureAdjustment;
  80289. var defines = "#define ";
  80290. if (_this._operator === TonemappingOperator.Hable)
  80291. defines += "HABLE_TONEMAPPING";
  80292. else if (_this._operator === TonemappingOperator.Reinhard)
  80293. defines += "REINHARD_TONEMAPPING";
  80294. else if (_this._operator === TonemappingOperator.HejiDawson)
  80295. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  80296. else if (_this._operator === TonemappingOperator.Photographic)
  80297. defines += "PHOTOGRAPHIC_TONEMAPPING";
  80298. //sadly a second call to create the effect.
  80299. _this.updateEffect(defines);
  80300. _this.onApply = function (effect) {
  80301. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  80302. };
  80303. return _this;
  80304. }
  80305. return TonemapPostProcess;
  80306. }(BABYLON.PostProcess));
  80307. BABYLON.TonemapPostProcess = TonemapPostProcess;
  80308. })(BABYLON || (BABYLON = {}));
  80309. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  80310. var BABYLON;
  80311. (function (BABYLON) {
  80312. var DisplayPassPostProcess = /** @class */ (function (_super) {
  80313. __extends(DisplayPassPostProcess, _super);
  80314. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  80315. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  80316. }
  80317. return DisplayPassPostProcess;
  80318. }(BABYLON.PostProcess));
  80319. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  80320. })(BABYLON || (BABYLON = {}));
  80321. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  80322. var BABYLON;
  80323. (function (BABYLON) {
  80324. var HighlightsPostProcess = /** @class */ (function (_super) {
  80325. __extends(HighlightsPostProcess, _super);
  80326. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  80327. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80328. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  80329. }
  80330. return HighlightsPostProcess;
  80331. }(BABYLON.PostProcess));
  80332. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  80333. })(BABYLON || (BABYLON = {}));
  80334. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  80335. var BABYLON;
  80336. (function (BABYLON) {
  80337. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  80338. __extends(ImageProcessingPostProcess, _super);
  80339. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  80340. if (camera === void 0) { camera = null; }
  80341. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80342. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  80343. _this._fromLinearSpace = true;
  80344. /**
  80345. * Defines cache preventing GC.
  80346. */
  80347. _this._defines = {
  80348. IMAGEPROCESSING: false,
  80349. VIGNETTE: false,
  80350. VIGNETTEBLENDMODEMULTIPLY: false,
  80351. VIGNETTEBLENDMODEOPAQUE: false,
  80352. TONEMAPPING: false,
  80353. CONTRAST: false,
  80354. COLORCURVES: false,
  80355. COLORGRADING: false,
  80356. COLORGRADING3D: false,
  80357. FROMLINEARSPACE: false,
  80358. SAMPLER3DGREENDEPTH: false,
  80359. SAMPLER3DBGRMAP: false,
  80360. IMAGEPROCESSINGPOSTPROCESS: false,
  80361. EXPOSURE: false,
  80362. };
  80363. // Setup the configuration as forced by the constructor. This would then not force the
  80364. // scene materials output in linear space and let untouched the default forward pass.
  80365. if (imageProcessingConfiguration) {
  80366. imageProcessingConfiguration.applyByPostProcess = true;
  80367. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  80368. // This will cause the shader to be compiled
  80369. _this.fromLinearSpace = false;
  80370. }
  80371. // Setup the default processing configuration to the scene.
  80372. else {
  80373. _this._attachImageProcessingConfiguration(null, true);
  80374. _this.imageProcessingConfiguration.applyByPostProcess = true;
  80375. }
  80376. _this.onApply = function (effect) {
  80377. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  80378. };
  80379. return _this;
  80380. }
  80381. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  80382. /**
  80383. * Gets the image processing configuration used either in this material.
  80384. */
  80385. get: function () {
  80386. return this._imageProcessingConfiguration;
  80387. },
  80388. /**
  80389. * Sets the Default image processing configuration used either in the this material.
  80390. *
  80391. * If sets to null, the scene one is in use.
  80392. */
  80393. set: function (value) {
  80394. this._attachImageProcessingConfiguration(value);
  80395. },
  80396. enumerable: true,
  80397. configurable: true
  80398. });
  80399. /**
  80400. * Attaches a new image processing configuration to the PBR Material.
  80401. * @param configuration
  80402. */
  80403. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  80404. var _this = this;
  80405. if (doNotBuild === void 0) { doNotBuild = false; }
  80406. if (configuration === this._imageProcessingConfiguration) {
  80407. return;
  80408. }
  80409. // Detaches observer.
  80410. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80411. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80412. }
  80413. // Pick the scene configuration if needed.
  80414. if (!configuration) {
  80415. var scene = null;
  80416. var engine = this.getEngine();
  80417. var camera = this.getCamera();
  80418. if (camera) {
  80419. scene = camera.getScene();
  80420. }
  80421. else if (engine && engine.scenes) {
  80422. var scenes = engine.scenes;
  80423. scene = scenes[scenes.length - 1];
  80424. }
  80425. else {
  80426. scene = BABYLON.Engine.LastCreatedScene;
  80427. }
  80428. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  80429. }
  80430. else {
  80431. this._imageProcessingConfiguration = configuration;
  80432. }
  80433. // Attaches observer.
  80434. if (this._imageProcessingConfiguration) {
  80435. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80436. _this._updateParameters();
  80437. });
  80438. }
  80439. // Ensure the effect will be rebuilt.
  80440. if (!doNotBuild) {
  80441. this._updateParameters();
  80442. }
  80443. };
  80444. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  80445. /**
  80446. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80447. */
  80448. get: function () {
  80449. return this.imageProcessingConfiguration.colorCurves;
  80450. },
  80451. /**
  80452. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80453. */
  80454. set: function (value) {
  80455. this.imageProcessingConfiguration.colorCurves = value;
  80456. },
  80457. enumerable: true,
  80458. configurable: true
  80459. });
  80460. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  80461. /**
  80462. * Gets wether the color curves effect is enabled.
  80463. */
  80464. get: function () {
  80465. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80466. },
  80467. /**
  80468. * Sets wether the color curves effect is enabled.
  80469. */
  80470. set: function (value) {
  80471. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80472. },
  80473. enumerable: true,
  80474. configurable: true
  80475. });
  80476. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  80477. /**
  80478. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80479. */
  80480. get: function () {
  80481. return this.imageProcessingConfiguration.colorGradingTexture;
  80482. },
  80483. /**
  80484. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80485. */
  80486. set: function (value) {
  80487. this.imageProcessingConfiguration.colorGradingTexture = value;
  80488. },
  80489. enumerable: true,
  80490. configurable: true
  80491. });
  80492. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  80493. /**
  80494. * Gets wether the color grading effect is enabled.
  80495. */
  80496. get: function () {
  80497. return this.imageProcessingConfiguration.colorGradingEnabled;
  80498. },
  80499. /**
  80500. * Gets wether the color grading effect is enabled.
  80501. */
  80502. set: function (value) {
  80503. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80504. },
  80505. enumerable: true,
  80506. configurable: true
  80507. });
  80508. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  80509. /**
  80510. * Gets exposure used in the effect.
  80511. */
  80512. get: function () {
  80513. return this.imageProcessingConfiguration.exposure;
  80514. },
  80515. /**
  80516. * Sets exposure used in the effect.
  80517. */
  80518. set: function (value) {
  80519. this.imageProcessingConfiguration.exposure = value;
  80520. },
  80521. enumerable: true,
  80522. configurable: true
  80523. });
  80524. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  80525. /**
  80526. * Gets wether tonemapping is enabled or not.
  80527. */
  80528. get: function () {
  80529. return this._imageProcessingConfiguration.toneMappingEnabled;
  80530. },
  80531. /**
  80532. * Sets wether tonemapping is enabled or not
  80533. */
  80534. set: function (value) {
  80535. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80536. },
  80537. enumerable: true,
  80538. configurable: true
  80539. });
  80540. ;
  80541. ;
  80542. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  80543. /**
  80544. * Gets contrast used in the effect.
  80545. */
  80546. get: function () {
  80547. return this.imageProcessingConfiguration.contrast;
  80548. },
  80549. /**
  80550. * Sets contrast used in the effect.
  80551. */
  80552. set: function (value) {
  80553. this.imageProcessingConfiguration.contrast = value;
  80554. },
  80555. enumerable: true,
  80556. configurable: true
  80557. });
  80558. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  80559. /**
  80560. * Gets Vignette stretch size.
  80561. */
  80562. get: function () {
  80563. return this.imageProcessingConfiguration.vignetteStretch;
  80564. },
  80565. /**
  80566. * Sets Vignette stretch size.
  80567. */
  80568. set: function (value) {
  80569. this.imageProcessingConfiguration.vignetteStretch = value;
  80570. },
  80571. enumerable: true,
  80572. configurable: true
  80573. });
  80574. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  80575. /**
  80576. * Gets Vignette centre X Offset.
  80577. */
  80578. get: function () {
  80579. return this.imageProcessingConfiguration.vignetteCentreX;
  80580. },
  80581. /**
  80582. * Sets Vignette centre X Offset.
  80583. */
  80584. set: function (value) {
  80585. this.imageProcessingConfiguration.vignetteCentreX = value;
  80586. },
  80587. enumerable: true,
  80588. configurable: true
  80589. });
  80590. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  80591. /**
  80592. * Gets Vignette centre Y Offset.
  80593. */
  80594. get: function () {
  80595. return this.imageProcessingConfiguration.vignetteCentreY;
  80596. },
  80597. /**
  80598. * Sets Vignette centre Y Offset.
  80599. */
  80600. set: function (value) {
  80601. this.imageProcessingConfiguration.vignetteCentreY = value;
  80602. },
  80603. enumerable: true,
  80604. configurable: true
  80605. });
  80606. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  80607. /**
  80608. * Gets Vignette weight or intensity of the vignette effect.
  80609. */
  80610. get: function () {
  80611. return this.imageProcessingConfiguration.vignetteWeight;
  80612. },
  80613. /**
  80614. * Sets Vignette weight or intensity of the vignette effect.
  80615. */
  80616. set: function (value) {
  80617. this.imageProcessingConfiguration.vignetteWeight = value;
  80618. },
  80619. enumerable: true,
  80620. configurable: true
  80621. });
  80622. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  80623. /**
  80624. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80625. * if vignetteEnabled is set to true.
  80626. */
  80627. get: function () {
  80628. return this.imageProcessingConfiguration.vignetteColor;
  80629. },
  80630. /**
  80631. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80632. * if vignetteEnabled is set to true.
  80633. */
  80634. set: function (value) {
  80635. this.imageProcessingConfiguration.vignetteColor = value;
  80636. },
  80637. enumerable: true,
  80638. configurable: true
  80639. });
  80640. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  80641. /**
  80642. * Gets Camera field of view used by the Vignette effect.
  80643. */
  80644. get: function () {
  80645. return this.imageProcessingConfiguration.vignetteCameraFov;
  80646. },
  80647. /**
  80648. * Sets Camera field of view used by the Vignette effect.
  80649. */
  80650. set: function (value) {
  80651. this.imageProcessingConfiguration.vignetteCameraFov = value;
  80652. },
  80653. enumerable: true,
  80654. configurable: true
  80655. });
  80656. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  80657. /**
  80658. * Gets the vignette blend mode allowing different kind of effect.
  80659. */
  80660. get: function () {
  80661. return this.imageProcessingConfiguration.vignetteBlendMode;
  80662. },
  80663. /**
  80664. * Sets the vignette blend mode allowing different kind of effect.
  80665. */
  80666. set: function (value) {
  80667. this.imageProcessingConfiguration.vignetteBlendMode = value;
  80668. },
  80669. enumerable: true,
  80670. configurable: true
  80671. });
  80672. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  80673. /**
  80674. * Gets wether the vignette effect is enabled.
  80675. */
  80676. get: function () {
  80677. return this.imageProcessingConfiguration.vignetteEnabled;
  80678. },
  80679. /**
  80680. * Sets wether the vignette effect is enabled.
  80681. */
  80682. set: function (value) {
  80683. this.imageProcessingConfiguration.vignetteEnabled = value;
  80684. },
  80685. enumerable: true,
  80686. configurable: true
  80687. });
  80688. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  80689. /**
  80690. * Gets wether the input of the processing is in Gamma or Linear Space.
  80691. */
  80692. get: function () {
  80693. return this._fromLinearSpace;
  80694. },
  80695. /**
  80696. * Sets wether the input of the processing is in Gamma or Linear Space.
  80697. */
  80698. set: function (value) {
  80699. if (this._fromLinearSpace === value) {
  80700. return;
  80701. }
  80702. this._fromLinearSpace = value;
  80703. this._updateParameters();
  80704. },
  80705. enumerable: true,
  80706. configurable: true
  80707. });
  80708. ImageProcessingPostProcess.prototype.getClassName = function () {
  80709. return "ImageProcessingPostProcess";
  80710. };
  80711. ImageProcessingPostProcess.prototype._updateParameters = function () {
  80712. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  80713. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  80714. var defines = "";
  80715. for (var define in this._defines) {
  80716. if (this._defines[define]) {
  80717. defines += "#define " + define + ";\r\n";
  80718. }
  80719. }
  80720. var samplers = ["textureSampler"];
  80721. var uniforms = ["scale"];
  80722. if (BABYLON.ImageProcessingConfiguration) {
  80723. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  80724. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  80725. }
  80726. this.updateEffect(defines, uniforms, samplers);
  80727. };
  80728. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  80729. _super.prototype.dispose.call(this, camera);
  80730. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80731. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80732. }
  80733. if (this._imageProcessingConfiguration) {
  80734. this.imageProcessingConfiguration.applyByPostProcess = false;
  80735. }
  80736. };
  80737. __decorate([
  80738. BABYLON.serialize()
  80739. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  80740. return ImageProcessingPostProcess;
  80741. }(BABYLON.PostProcess));
  80742. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  80743. })(BABYLON || (BABYLON = {}));
  80744. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  80745. var BABYLON;
  80746. (function (BABYLON) {
  80747. /**
  80748. * Class used to store bone information
  80749. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80750. */
  80751. var Bone = /** @class */ (function (_super) {
  80752. __extends(Bone, _super);
  80753. /**
  80754. * Create a new bone
  80755. * @param name defines the bone name
  80756. * @param skeleton defines the parent skeleton
  80757. * @param parentBone defines the parent (can be null if the bone is the root)
  80758. * @param localMatrix defines the local matrix
  80759. * @param restPose defines the rest pose matrix
  80760. * @param baseMatrix defines the base matrix
  80761. * @param index defines index of the bone in the hiearchy
  80762. */
  80763. function Bone(
  80764. /**
  80765. * defines the bone name
  80766. */
  80767. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  80768. if (parentBone === void 0) { parentBone = null; }
  80769. if (localMatrix === void 0) { localMatrix = null; }
  80770. if (restPose === void 0) { restPose = null; }
  80771. if (baseMatrix === void 0) { baseMatrix = null; }
  80772. if (index === void 0) { index = null; }
  80773. var _this = _super.call(this, name, skeleton.getScene()) || this;
  80774. _this.name = name;
  80775. /**
  80776. * Gets the list of child bones
  80777. */
  80778. _this.children = new Array();
  80779. /** Gets the animations associated with this bone */
  80780. _this.animations = new Array();
  80781. /**
  80782. * @hidden Internal only
  80783. * Set this value to map this bone to a different index in the transform matrices
  80784. * Set this value to -1 to exclude the bone from the transform matrices
  80785. */
  80786. _this._index = null;
  80787. _this._absoluteTransform = new BABYLON.Matrix();
  80788. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  80789. _this._scalingDeterminant = 1;
  80790. _this._worldTransform = new BABYLON.Matrix();
  80791. _this._needToDecompose = true;
  80792. _this._needToCompose = false;
  80793. _this._skeleton = skeleton;
  80794. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  80795. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  80796. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  80797. _this._index = index;
  80798. skeleton.bones.push(_this);
  80799. _this.setParent(parentBone, false);
  80800. if (baseMatrix || localMatrix) {
  80801. _this._updateDifferenceMatrix();
  80802. }
  80803. return _this;
  80804. }
  80805. Object.defineProperty(Bone.prototype, "_matrix", {
  80806. /** @hidden */
  80807. get: function () {
  80808. this._compose();
  80809. return this._localMatrix;
  80810. },
  80811. /** @hidden */
  80812. set: function (value) {
  80813. this._localMatrix.copyFrom(value);
  80814. this._needToDecompose = true;
  80815. },
  80816. enumerable: true,
  80817. configurable: true
  80818. });
  80819. // Members
  80820. /**
  80821. * Gets the parent skeleton
  80822. * @returns a skeleton
  80823. */
  80824. Bone.prototype.getSkeleton = function () {
  80825. return this._skeleton;
  80826. };
  80827. /**
  80828. * Gets parent bone
  80829. * @returns a bone or null if the bone is the root of the bone hierarchy
  80830. */
  80831. Bone.prototype.getParent = function () {
  80832. return this._parent;
  80833. };
  80834. /**
  80835. * Sets the parent bone
  80836. * @param parent defines the parent (can be null if the bone is the root)
  80837. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  80838. */
  80839. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  80840. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  80841. if (this._parent === parent) {
  80842. return;
  80843. }
  80844. if (this._parent) {
  80845. var index = this._parent.children.indexOf(this);
  80846. if (index !== -1) {
  80847. this._parent.children.splice(index, 1);
  80848. }
  80849. }
  80850. this._parent = parent;
  80851. if (this._parent) {
  80852. this._parent.children.push(this);
  80853. }
  80854. if (updateDifferenceMatrix) {
  80855. this._updateDifferenceMatrix();
  80856. }
  80857. this.markAsDirty();
  80858. };
  80859. /**
  80860. * Gets the local matrix
  80861. * @returns a matrix
  80862. */
  80863. Bone.prototype.getLocalMatrix = function () {
  80864. this._compose();
  80865. return this._localMatrix;
  80866. };
  80867. /**
  80868. * Gets the base matrix (initial matrix which remains unchanged)
  80869. * @returns a matrix
  80870. */
  80871. Bone.prototype.getBaseMatrix = function () {
  80872. return this._baseMatrix;
  80873. };
  80874. /**
  80875. * Gets the rest pose matrix
  80876. * @returns a matrix
  80877. */
  80878. Bone.prototype.getRestPose = function () {
  80879. return this._restPose;
  80880. };
  80881. /**
  80882. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  80883. */
  80884. Bone.prototype.getWorldMatrix = function () {
  80885. return this._worldTransform;
  80886. };
  80887. /**
  80888. * Sets the local matrix to rest pose matrix
  80889. */
  80890. Bone.prototype.returnToRest = function () {
  80891. this.updateMatrix(this._restPose.clone());
  80892. };
  80893. /**
  80894. * Gets the inverse of the absolute transform matrix.
  80895. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  80896. * @returns a matrix
  80897. */
  80898. Bone.prototype.getInvertedAbsoluteTransform = function () {
  80899. return this._invertedAbsoluteTransform;
  80900. };
  80901. /**
  80902. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  80903. * @returns a matrix
  80904. */
  80905. Bone.prototype.getAbsoluteTransform = function () {
  80906. return this._absoluteTransform;
  80907. };
  80908. Object.defineProperty(Bone.prototype, "position", {
  80909. // Properties (matches AbstractMesh properties)
  80910. /** Gets or sets current position (in local space) */
  80911. get: function () {
  80912. this._decompose();
  80913. return this._localPosition;
  80914. },
  80915. set: function (newPosition) {
  80916. this._decompose();
  80917. this._localPosition.copyFrom(newPosition);
  80918. this._markAsDirtyAndCompose();
  80919. },
  80920. enumerable: true,
  80921. configurable: true
  80922. });
  80923. Object.defineProperty(Bone.prototype, "rotation", {
  80924. /** Gets or sets current rotation (in local space) */
  80925. get: function () {
  80926. return this.getRotation();
  80927. },
  80928. set: function (newRotation) {
  80929. this.setRotation(newRotation);
  80930. },
  80931. enumerable: true,
  80932. configurable: true
  80933. });
  80934. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  80935. /** Gets or sets current rotation quaternion (in local space) */
  80936. get: function () {
  80937. this._decompose();
  80938. return this._localRotation;
  80939. },
  80940. set: function (newRotation) {
  80941. this.setRotationQuaternion(newRotation);
  80942. },
  80943. enumerable: true,
  80944. configurable: true
  80945. });
  80946. Object.defineProperty(Bone.prototype, "scaling", {
  80947. /** Gets or sets current scaling (in local space) */
  80948. get: function () {
  80949. return this.getScale();
  80950. },
  80951. set: function (newScaling) {
  80952. this.setScale(newScaling);
  80953. },
  80954. enumerable: true,
  80955. configurable: true
  80956. });
  80957. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  80958. /**
  80959. * Gets the animation properties override
  80960. */
  80961. get: function () {
  80962. return this._skeleton.animationPropertiesOverride;
  80963. },
  80964. enumerable: true,
  80965. configurable: true
  80966. });
  80967. // Methods
  80968. Bone.prototype._decompose = function () {
  80969. if (!this._needToDecompose) {
  80970. return;
  80971. }
  80972. this._needToDecompose = false;
  80973. if (!this._localScaling) {
  80974. this._localScaling = BABYLON.Vector3.Zero();
  80975. this._localRotation = BABYLON.Quaternion.Zero();
  80976. this._localPosition = BABYLON.Vector3.Zero();
  80977. }
  80978. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  80979. };
  80980. Bone.prototype._compose = function () {
  80981. if (!this._needToCompose) {
  80982. return;
  80983. }
  80984. this._needToCompose = false;
  80985. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  80986. };
  80987. /**
  80988. * Update the base and local matrices
  80989. * @param matrix defines the new base or local matrix
  80990. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  80991. * @param updateLocalMatrix defines if the local matrix should be updated
  80992. */
  80993. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  80994. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  80995. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  80996. this._baseMatrix.copyFrom(matrix);
  80997. if (updateDifferenceMatrix) {
  80998. this._updateDifferenceMatrix();
  80999. }
  81000. if (updateLocalMatrix) {
  81001. this._localMatrix.copyFrom(matrix);
  81002. this._markAsDirtyAndDecompose();
  81003. }
  81004. else {
  81005. this.markAsDirty();
  81006. }
  81007. };
  81008. /** @hidden */
  81009. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  81010. if (updateChildren === void 0) { updateChildren = true; }
  81011. if (!rootMatrix) {
  81012. rootMatrix = this._baseMatrix;
  81013. }
  81014. if (this._parent) {
  81015. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81016. }
  81017. else {
  81018. this._absoluteTransform.copyFrom(rootMatrix);
  81019. }
  81020. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  81021. if (updateChildren) {
  81022. for (var index = 0; index < this.children.length; index++) {
  81023. this.children[index]._updateDifferenceMatrix();
  81024. }
  81025. }
  81026. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  81027. };
  81028. /**
  81029. * Flag the bone as dirty (Forcing it to update everything)
  81030. */
  81031. Bone.prototype.markAsDirty = function () {
  81032. this._currentRenderId++;
  81033. this._childRenderId++;
  81034. this._skeleton._markAsDirty();
  81035. };
  81036. Bone.prototype._markAsDirtyAndCompose = function () {
  81037. this.markAsDirty();
  81038. this._needToCompose = true;
  81039. };
  81040. Bone.prototype._markAsDirtyAndDecompose = function () {
  81041. this.markAsDirty();
  81042. this._needToDecompose = true;
  81043. };
  81044. /**
  81045. * Copy an animation range from another bone
  81046. * @param source defines the source bone
  81047. * @param rangeName defines the range name to copy
  81048. * @param frameOffset defines the frame offset
  81049. * @param rescaleAsRequired defines if rescaling must be applied if required
  81050. * @param skelDimensionsRatio defines the scaling ratio
  81051. * @returns true if operation was successful
  81052. */
  81053. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  81054. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81055. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  81056. // all animation may be coming from a library skeleton, so may need to create animation
  81057. if (this.animations.length === 0) {
  81058. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  81059. this.animations[0].setKeys([]);
  81060. }
  81061. // get animation info / verify there is such a range from the source bone
  81062. var sourceRange = source.animations[0].getRange(rangeName);
  81063. if (!sourceRange) {
  81064. return false;
  81065. }
  81066. var from = sourceRange.from;
  81067. var to = sourceRange.to;
  81068. var sourceKeys = source.animations[0].getKeys();
  81069. // rescaling prep
  81070. var sourceBoneLength = source.length;
  81071. var sourceParent = source.getParent();
  81072. var parent = this.getParent();
  81073. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  81074. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  81075. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  81076. var destKeys = this.animations[0].getKeys();
  81077. // loop vars declaration
  81078. var orig;
  81079. var origTranslation;
  81080. var mat;
  81081. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  81082. orig = sourceKeys[key];
  81083. if (orig.frame >= from && orig.frame <= to) {
  81084. if (rescaleAsRequired) {
  81085. mat = orig.value.clone();
  81086. // scale based on parent ratio, when bone has parent
  81087. if (parentScalingReqd) {
  81088. origTranslation = mat.getTranslation();
  81089. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  81090. // scale based on skeleton dimension ratio when root bone, and value is passed
  81091. }
  81092. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  81093. origTranslation = mat.getTranslation();
  81094. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  81095. // use original when root bone, and no data for skelDimensionsRatio
  81096. }
  81097. else {
  81098. mat = orig.value;
  81099. }
  81100. }
  81101. else {
  81102. mat = orig.value;
  81103. }
  81104. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  81105. }
  81106. }
  81107. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  81108. return true;
  81109. };
  81110. /**
  81111. * Translate the bone in local or world space
  81112. * @param vec The amount to translate the bone
  81113. * @param space The space that the translation is in
  81114. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81115. */
  81116. Bone.prototype.translate = function (vec, space, mesh) {
  81117. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81118. var lm = this.getLocalMatrix();
  81119. if (space == BABYLON.Space.LOCAL) {
  81120. lm.m[12] += vec.x;
  81121. lm.m[13] += vec.y;
  81122. lm.m[14] += vec.z;
  81123. }
  81124. else {
  81125. var wm = null;
  81126. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81127. if (mesh) {
  81128. wm = mesh.getWorldMatrix();
  81129. }
  81130. this._skeleton.computeAbsoluteTransforms();
  81131. var tmat = Bone._tmpMats[0];
  81132. var tvec = Bone._tmpVecs[0];
  81133. if (this._parent) {
  81134. if (mesh && wm) {
  81135. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81136. tmat.multiplyToRef(wm, tmat);
  81137. }
  81138. else {
  81139. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81140. }
  81141. }
  81142. tmat.m[12] = 0;
  81143. tmat.m[13] = 0;
  81144. tmat.m[14] = 0;
  81145. tmat.invert();
  81146. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  81147. lm.m[12] += tvec.x;
  81148. lm.m[13] += tvec.y;
  81149. lm.m[14] += tvec.z;
  81150. }
  81151. this._markAsDirtyAndDecompose();
  81152. };
  81153. /**
  81154. * Set the postion of the bone in local or world space
  81155. * @param position The position to set the bone
  81156. * @param space The space that the position is in
  81157. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81158. */
  81159. Bone.prototype.setPosition = function (position, space, mesh) {
  81160. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81161. var lm = this.getLocalMatrix();
  81162. if (space == BABYLON.Space.LOCAL) {
  81163. lm.m[12] = position.x;
  81164. lm.m[13] = position.y;
  81165. lm.m[14] = position.z;
  81166. }
  81167. else {
  81168. var wm = null;
  81169. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81170. if (mesh) {
  81171. wm = mesh.getWorldMatrix();
  81172. }
  81173. this._skeleton.computeAbsoluteTransforms();
  81174. var tmat = Bone._tmpMats[0];
  81175. var vec = Bone._tmpVecs[0];
  81176. if (this._parent) {
  81177. if (mesh && wm) {
  81178. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81179. tmat.multiplyToRef(wm, tmat);
  81180. }
  81181. else {
  81182. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81183. }
  81184. }
  81185. tmat.invert();
  81186. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  81187. lm.m[12] = vec.x;
  81188. lm.m[13] = vec.y;
  81189. lm.m[14] = vec.z;
  81190. }
  81191. this._markAsDirtyAndDecompose();
  81192. };
  81193. /**
  81194. * Set the absolute position of the bone (world space)
  81195. * @param position The position to set the bone
  81196. * @param mesh The mesh that this bone is attached to
  81197. */
  81198. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  81199. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  81200. };
  81201. /**
  81202. * Scale the bone on the x, y and z axes (in local space)
  81203. * @param x The amount to scale the bone on the x axis
  81204. * @param y The amount to scale the bone on the y axis
  81205. * @param z The amount to scale the bone on the z axis
  81206. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  81207. */
  81208. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  81209. if (scaleChildren === void 0) { scaleChildren = false; }
  81210. var locMat = this.getLocalMatrix();
  81211. // Apply new scaling on top of current local matrix
  81212. var scaleMat = Bone._tmpMats[0];
  81213. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  81214. scaleMat.multiplyToRef(locMat, locMat);
  81215. // Invert scaling matrix and apply the inverse to all children
  81216. scaleMat.invert();
  81217. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  81218. var child = _a[_i];
  81219. var cm = child.getLocalMatrix();
  81220. cm.multiplyToRef(scaleMat, cm);
  81221. cm.m[12] *= x;
  81222. cm.m[13] *= y;
  81223. cm.m[14] *= z;
  81224. child._markAsDirtyAndDecompose();
  81225. }
  81226. this._markAsDirtyAndDecompose();
  81227. if (scaleChildren) {
  81228. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  81229. var child = _c[_b];
  81230. child.scale(x, y, z, scaleChildren);
  81231. }
  81232. }
  81233. };
  81234. /**
  81235. * Set the bone scaling in local space
  81236. * @param scale defines the scaling vector
  81237. */
  81238. Bone.prototype.setScale = function (scale) {
  81239. this._decompose();
  81240. this._localScaling.copyFrom(scale);
  81241. this._markAsDirtyAndCompose();
  81242. };
  81243. /**
  81244. * Gets the current scaling in local space
  81245. * @returns the current scaling vector
  81246. */
  81247. Bone.prototype.getScale = function () {
  81248. this._decompose();
  81249. return this._localScaling;
  81250. };
  81251. /**
  81252. * Gets the current scaling in local space and stores it in a target vector
  81253. * @param result defines the target vector
  81254. */
  81255. Bone.prototype.getScaleToRef = function (result) {
  81256. this._decompose();
  81257. result.copyFrom(this._localScaling);
  81258. };
  81259. /**
  81260. * Set the yaw, pitch, and roll of the bone in local or world space
  81261. * @param yaw The rotation of the bone on the y axis
  81262. * @param pitch The rotation of the bone on the x axis
  81263. * @param roll The rotation of the bone on the z axis
  81264. * @param space The space that the axes of rotation are in
  81265. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81266. */
  81267. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  81268. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81269. if (space === BABYLON.Space.LOCAL) {
  81270. var quat = Bone._tmpQuat;
  81271. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  81272. this.setRotationQuaternion(quat, space, mesh);
  81273. return;
  81274. }
  81275. var rotMatInv = Bone._tmpMats[0];
  81276. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81277. return;
  81278. }
  81279. var rotMat = Bone._tmpMats[1];
  81280. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  81281. rotMatInv.multiplyToRef(rotMat, rotMat);
  81282. this._rotateWithMatrix(rotMat, space, mesh);
  81283. };
  81284. /**
  81285. * Add a rotation to the bone on an axis in local or world space
  81286. * @param axis The axis to rotate the bone on
  81287. * @param amount The amount to rotate the bone
  81288. * @param space The space that the axis is in
  81289. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81290. */
  81291. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  81292. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81293. var rmat = Bone._tmpMats[0];
  81294. rmat.m[12] = 0;
  81295. rmat.m[13] = 0;
  81296. rmat.m[14] = 0;
  81297. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  81298. this._rotateWithMatrix(rmat, space, mesh);
  81299. };
  81300. /**
  81301. * Set the rotation of the bone to a particular axis angle in local or world space
  81302. * @param axis The axis to rotate the bone on
  81303. * @param angle The angle that the bone should be rotated to
  81304. * @param space The space that the axis is in
  81305. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81306. */
  81307. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  81308. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81309. if (space === BABYLON.Space.LOCAL) {
  81310. var quat = Bone._tmpQuat;
  81311. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  81312. this.setRotationQuaternion(quat, space, mesh);
  81313. return;
  81314. }
  81315. var rotMatInv = Bone._tmpMats[0];
  81316. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81317. return;
  81318. }
  81319. var rotMat = Bone._tmpMats[1];
  81320. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  81321. rotMatInv.multiplyToRef(rotMat, rotMat);
  81322. this._rotateWithMatrix(rotMat, space, mesh);
  81323. };
  81324. /**
  81325. * Set the euler rotation of the bone in local of world space
  81326. * @param rotation The euler rotation that the bone should be set to
  81327. * @param space The space that the rotation is in
  81328. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81329. */
  81330. Bone.prototype.setRotation = function (rotation, space, mesh) {
  81331. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81332. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  81333. };
  81334. /**
  81335. * Set the quaternion rotation of the bone in local of world space
  81336. * @param quat The quaternion rotation that the bone should be set to
  81337. * @param space The space that the rotation is in
  81338. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81339. */
  81340. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  81341. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81342. if (space === BABYLON.Space.LOCAL) {
  81343. this._decompose();
  81344. this._localRotation.copyFrom(quat);
  81345. this._markAsDirtyAndCompose();
  81346. return;
  81347. }
  81348. var rotMatInv = Bone._tmpMats[0];
  81349. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81350. return;
  81351. }
  81352. var rotMat = Bone._tmpMats[1];
  81353. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  81354. rotMatInv.multiplyToRef(rotMat, rotMat);
  81355. this._rotateWithMatrix(rotMat, space, mesh);
  81356. };
  81357. /**
  81358. * Set the rotation matrix of the bone in local of world space
  81359. * @param rotMat The rotation matrix that the bone should be set to
  81360. * @param space The space that the rotation is in
  81361. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81362. */
  81363. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  81364. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81365. if (space === BABYLON.Space.LOCAL) {
  81366. var quat = Bone._tmpQuat;
  81367. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  81368. this.setRotationQuaternion(quat, space, mesh);
  81369. return;
  81370. }
  81371. var rotMatInv = Bone._tmpMats[0];
  81372. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81373. return;
  81374. }
  81375. var rotMat2 = Bone._tmpMats[1];
  81376. rotMat2.copyFrom(rotMat);
  81377. rotMatInv.multiplyToRef(rotMat, rotMat2);
  81378. this._rotateWithMatrix(rotMat2, space, mesh);
  81379. };
  81380. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  81381. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81382. var lmat = this.getLocalMatrix();
  81383. var lx = lmat.m[12];
  81384. var ly = lmat.m[13];
  81385. var lz = lmat.m[14];
  81386. var parent = this.getParent();
  81387. var parentScale = Bone._tmpMats[3];
  81388. var parentScaleInv = Bone._tmpMats[4];
  81389. if (parent && space == BABYLON.Space.WORLD) {
  81390. if (mesh) {
  81391. parentScale.copyFrom(mesh.getWorldMatrix());
  81392. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  81393. }
  81394. else {
  81395. parentScale.copyFrom(parent.getAbsoluteTransform());
  81396. }
  81397. parentScaleInv.copyFrom(parentScale);
  81398. parentScaleInv.invert();
  81399. lmat.multiplyToRef(parentScale, lmat);
  81400. lmat.multiplyToRef(rmat, lmat);
  81401. lmat.multiplyToRef(parentScaleInv, lmat);
  81402. }
  81403. else {
  81404. if (space == BABYLON.Space.WORLD && mesh) {
  81405. parentScale.copyFrom(mesh.getWorldMatrix());
  81406. parentScaleInv.copyFrom(parentScale);
  81407. parentScaleInv.invert();
  81408. lmat.multiplyToRef(parentScale, lmat);
  81409. lmat.multiplyToRef(rmat, lmat);
  81410. lmat.multiplyToRef(parentScaleInv, lmat);
  81411. }
  81412. else {
  81413. lmat.multiplyToRef(rmat, lmat);
  81414. }
  81415. }
  81416. lmat.m[12] = lx;
  81417. lmat.m[13] = ly;
  81418. lmat.m[14] = lz;
  81419. this.computeAbsoluteTransforms();
  81420. this._markAsDirtyAndDecompose();
  81421. };
  81422. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  81423. var scaleMatrix = Bone._tmpMats[2];
  81424. rotMatInv.copyFrom(this.getAbsoluteTransform());
  81425. if (mesh) {
  81426. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  81427. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  81428. }
  81429. rotMatInv.invert();
  81430. if (isNaN(rotMatInv.m[0])) {
  81431. // Matrix failed to invert.
  81432. // This can happen if scale is zero for example.
  81433. return false;
  81434. }
  81435. scaleMatrix.m[0] *= this._scalingDeterminant;
  81436. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  81437. return true;
  81438. };
  81439. /**
  81440. * Get the position of the bone in local or world space
  81441. * @param space The space that the returned position is in
  81442. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81443. * @returns The position of the bone
  81444. */
  81445. Bone.prototype.getPosition = function (space, mesh) {
  81446. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81447. if (mesh === void 0) { mesh = null; }
  81448. var pos = BABYLON.Vector3.Zero();
  81449. this.getPositionToRef(space, mesh, pos);
  81450. return pos;
  81451. };
  81452. /**
  81453. * Copy the position of the bone to a vector3 in local or world space
  81454. * @param space The space that the returned position is in
  81455. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81456. * @param result The vector3 to copy the position to
  81457. */
  81458. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  81459. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81460. if (space == BABYLON.Space.LOCAL) {
  81461. var lm = this.getLocalMatrix();
  81462. result.x = lm.m[12];
  81463. result.y = lm.m[13];
  81464. result.z = lm.m[14];
  81465. }
  81466. else {
  81467. var wm = null;
  81468. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81469. if (mesh) {
  81470. wm = mesh.getWorldMatrix();
  81471. }
  81472. this._skeleton.computeAbsoluteTransforms();
  81473. var tmat = Bone._tmpMats[0];
  81474. if (mesh && wm) {
  81475. tmat.copyFrom(this.getAbsoluteTransform());
  81476. tmat.multiplyToRef(wm, tmat);
  81477. }
  81478. else {
  81479. tmat = this.getAbsoluteTransform();
  81480. }
  81481. result.x = tmat.m[12];
  81482. result.y = tmat.m[13];
  81483. result.z = tmat.m[14];
  81484. }
  81485. };
  81486. /**
  81487. * Get the absolute position of the bone (world space)
  81488. * @param mesh The mesh that this bone is attached to
  81489. * @returns The absolute position of the bone
  81490. */
  81491. Bone.prototype.getAbsolutePosition = function (mesh) {
  81492. if (mesh === void 0) { mesh = null; }
  81493. var pos = BABYLON.Vector3.Zero();
  81494. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  81495. return pos;
  81496. };
  81497. /**
  81498. * Copy the absolute position of the bone (world space) to the result param
  81499. * @param mesh The mesh that this bone is attached to
  81500. * @param result The vector3 to copy the absolute position to
  81501. */
  81502. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  81503. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  81504. };
  81505. /**
  81506. * Compute the absolute transforms of this bone and its children
  81507. */
  81508. Bone.prototype.computeAbsoluteTransforms = function () {
  81509. this._compose();
  81510. if (this._parent) {
  81511. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81512. }
  81513. else {
  81514. this._absoluteTransform.copyFrom(this._localMatrix);
  81515. var poseMatrix = this._skeleton.getPoseMatrix();
  81516. if (poseMatrix) {
  81517. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  81518. }
  81519. }
  81520. var children = this.children;
  81521. var len = children.length;
  81522. for (var i = 0; i < len; i++) {
  81523. children[i].computeAbsoluteTransforms();
  81524. }
  81525. };
  81526. /**
  81527. * Get the world direction from an axis that is in the local space of the bone
  81528. * @param localAxis The local direction that is used to compute the world direction
  81529. * @param mesh The mesh that this bone is attached to
  81530. * @returns The world direction
  81531. */
  81532. Bone.prototype.getDirection = function (localAxis, mesh) {
  81533. if (mesh === void 0) { mesh = null; }
  81534. var result = BABYLON.Vector3.Zero();
  81535. this.getDirectionToRef(localAxis, mesh, result);
  81536. return result;
  81537. };
  81538. /**
  81539. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  81540. * @param localAxis The local direction that is used to compute the world direction
  81541. * @param mesh The mesh that this bone is attached to
  81542. * @param result The vector3 that the world direction will be copied to
  81543. */
  81544. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  81545. if (mesh === void 0) { mesh = null; }
  81546. var wm = null;
  81547. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81548. if (mesh) {
  81549. wm = mesh.getWorldMatrix();
  81550. }
  81551. this._skeleton.computeAbsoluteTransforms();
  81552. var mat = Bone._tmpMats[0];
  81553. mat.copyFrom(this.getAbsoluteTransform());
  81554. if (mesh && wm) {
  81555. mat.multiplyToRef(wm, mat);
  81556. }
  81557. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  81558. result.normalize();
  81559. };
  81560. /**
  81561. * Get the euler rotation of the bone in local or world space
  81562. * @param space The space that the rotation should be in
  81563. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81564. * @returns The euler rotation
  81565. */
  81566. Bone.prototype.getRotation = function (space, mesh) {
  81567. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81568. if (mesh === void 0) { mesh = null; }
  81569. var result = BABYLON.Vector3.Zero();
  81570. this.getRotationToRef(space, mesh, result);
  81571. return result;
  81572. };
  81573. /**
  81574. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  81575. * @param space The space that the rotation should be in
  81576. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81577. * @param result The vector3 that the rotation should be copied to
  81578. */
  81579. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  81580. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81581. if (mesh === void 0) { mesh = null; }
  81582. var quat = Bone._tmpQuat;
  81583. this.getRotationQuaternionToRef(space, mesh, quat);
  81584. quat.toEulerAnglesToRef(result);
  81585. };
  81586. /**
  81587. * Get the quaternion rotation of the bone in either local or world space
  81588. * @param space The space that the rotation should be in
  81589. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81590. * @returns The quaternion rotation
  81591. */
  81592. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  81593. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81594. if (mesh === void 0) { mesh = null; }
  81595. var result = BABYLON.Quaternion.Identity();
  81596. this.getRotationQuaternionToRef(space, mesh, result);
  81597. return result;
  81598. };
  81599. /**
  81600. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  81601. * @param space The space that the rotation should be in
  81602. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81603. * @param result The quaternion that the rotation should be copied to
  81604. */
  81605. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  81606. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81607. if (mesh === void 0) { mesh = null; }
  81608. if (space == BABYLON.Space.LOCAL) {
  81609. this._decompose();
  81610. result.copyFrom(this._localRotation);
  81611. }
  81612. else {
  81613. var mat = Bone._tmpMats[0];
  81614. var amat = this.getAbsoluteTransform();
  81615. if (mesh) {
  81616. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81617. }
  81618. else {
  81619. mat.copyFrom(amat);
  81620. }
  81621. mat.m[0] *= this._scalingDeterminant;
  81622. mat.m[1] *= this._scalingDeterminant;
  81623. mat.m[2] *= this._scalingDeterminant;
  81624. mat.decompose(undefined, result, undefined);
  81625. }
  81626. };
  81627. /**
  81628. * Get the rotation matrix of the bone in local or world space
  81629. * @param space The space that the rotation should be in
  81630. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81631. * @returns The rotation matrix
  81632. */
  81633. Bone.prototype.getRotationMatrix = function (space, mesh) {
  81634. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81635. var result = BABYLON.Matrix.Identity();
  81636. this.getRotationMatrixToRef(space, mesh, result);
  81637. return result;
  81638. };
  81639. /**
  81640. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  81641. * @param space The space that the rotation should be in
  81642. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81643. * @param result The quaternion that the rotation should be copied to
  81644. */
  81645. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  81646. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81647. if (space == BABYLON.Space.LOCAL) {
  81648. this.getLocalMatrix().getRotationMatrixToRef(result);
  81649. }
  81650. else {
  81651. var mat = Bone._tmpMats[0];
  81652. var amat = this.getAbsoluteTransform();
  81653. if (mesh) {
  81654. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81655. }
  81656. else {
  81657. mat.copyFrom(amat);
  81658. }
  81659. mat.m[0] *= this._scalingDeterminant;
  81660. mat.m[1] *= this._scalingDeterminant;
  81661. mat.m[2] *= this._scalingDeterminant;
  81662. mat.getRotationMatrixToRef(result);
  81663. }
  81664. };
  81665. /**
  81666. * Get the world position of a point that is in the local space of the bone
  81667. * @param position The local position
  81668. * @param mesh The mesh that this bone is attached to
  81669. * @returns The world position
  81670. */
  81671. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  81672. if (mesh === void 0) { mesh = null; }
  81673. var result = BABYLON.Vector3.Zero();
  81674. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  81675. return result;
  81676. };
  81677. /**
  81678. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  81679. * @param position The local position
  81680. * @param mesh The mesh that this bone is attached to
  81681. * @param result The vector3 that the world position should be copied to
  81682. */
  81683. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  81684. if (mesh === void 0) { mesh = null; }
  81685. var wm = null;
  81686. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81687. if (mesh) {
  81688. wm = mesh.getWorldMatrix();
  81689. }
  81690. this._skeleton.computeAbsoluteTransforms();
  81691. var tmat = Bone._tmpMats[0];
  81692. if (mesh && wm) {
  81693. tmat.copyFrom(this.getAbsoluteTransform());
  81694. tmat.multiplyToRef(wm, tmat);
  81695. }
  81696. else {
  81697. tmat = this.getAbsoluteTransform();
  81698. }
  81699. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81700. };
  81701. /**
  81702. * Get the local position of a point that is in world space
  81703. * @param position The world position
  81704. * @param mesh The mesh that this bone is attached to
  81705. * @returns The local position
  81706. */
  81707. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  81708. if (mesh === void 0) { mesh = null; }
  81709. var result = BABYLON.Vector3.Zero();
  81710. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  81711. return result;
  81712. };
  81713. /**
  81714. * Get the local position of a point that is in world space and copy it to the result param
  81715. * @param position The world position
  81716. * @param mesh The mesh that this bone is attached to
  81717. * @param result The vector3 that the local position should be copied to
  81718. */
  81719. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  81720. if (mesh === void 0) { mesh = null; }
  81721. var wm = null;
  81722. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81723. if (mesh) {
  81724. wm = mesh.getWorldMatrix();
  81725. }
  81726. this._skeleton.computeAbsoluteTransforms();
  81727. var tmat = Bone._tmpMats[0];
  81728. tmat.copyFrom(this.getAbsoluteTransform());
  81729. if (mesh && wm) {
  81730. tmat.multiplyToRef(wm, tmat);
  81731. }
  81732. tmat.invert();
  81733. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81734. };
  81735. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81736. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  81737. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81738. return Bone;
  81739. }(BABYLON.Node));
  81740. BABYLON.Bone = Bone;
  81741. })(BABYLON || (BABYLON = {}));
  81742. //# sourceMappingURL=babylon.bone.js.map
  81743. var BABYLON;
  81744. (function (BABYLON) {
  81745. /**
  81746. * Class used to apply inverse kinematics to bones
  81747. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  81748. */
  81749. var BoneIKController = /** @class */ (function () {
  81750. /**
  81751. * Creates a new BoneIKController
  81752. * @param mesh defines the mesh to control
  81753. * @param bone defines the bone to control
  81754. * @param options defines options to set up the controller
  81755. */
  81756. function BoneIKController(mesh, bone, options) {
  81757. /**
  81758. * Gets or sets the target position
  81759. */
  81760. this.targetPosition = BABYLON.Vector3.Zero();
  81761. /**
  81762. * Gets or sets the pole target position
  81763. */
  81764. this.poleTargetPosition = BABYLON.Vector3.Zero();
  81765. /**
  81766. * Gets or sets the pole target local offset
  81767. */
  81768. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  81769. /**
  81770. * Gets or sets the pole angle
  81771. */
  81772. this.poleAngle = 0;
  81773. /**
  81774. * 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)
  81775. */
  81776. this.slerpAmount = 1;
  81777. this._bone1Quat = BABYLON.Quaternion.Identity();
  81778. this._bone1Mat = BABYLON.Matrix.Identity();
  81779. this._bone2Ang = Math.PI;
  81780. this._maxAngle = Math.PI;
  81781. this._rightHandedSystem = false;
  81782. this._bendAxis = BABYLON.Vector3.Right();
  81783. this._slerping = false;
  81784. this._adjustRoll = 0;
  81785. this._bone2 = bone;
  81786. this._bone1 = bone.getParent();
  81787. if (!this._bone1) {
  81788. return;
  81789. }
  81790. this.mesh = mesh;
  81791. var bonePos = bone.getPosition();
  81792. if (bone.getAbsoluteTransform().determinant() > 0) {
  81793. this._rightHandedSystem = true;
  81794. this._bendAxis.x = 0;
  81795. this._bendAxis.y = 0;
  81796. this._bendAxis.z = -1;
  81797. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  81798. this._adjustRoll = Math.PI * .5;
  81799. this._bendAxis.z = 1;
  81800. }
  81801. }
  81802. if (this._bone1.length) {
  81803. var boneScale1 = this._bone1.getScale();
  81804. var boneScale2 = this._bone2.getScale();
  81805. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  81806. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  81807. }
  81808. else if (this._bone1.children[0]) {
  81809. mesh.computeWorldMatrix(true);
  81810. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  81811. var pos2 = this._bone2.getAbsolutePosition(mesh);
  81812. var pos3 = this._bone1.getAbsolutePosition(mesh);
  81813. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  81814. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  81815. }
  81816. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  81817. this.maxAngle = Math.PI;
  81818. if (options) {
  81819. if (options.targetMesh) {
  81820. this.targetMesh = options.targetMesh;
  81821. this.targetMesh.computeWorldMatrix(true);
  81822. }
  81823. if (options.poleTargetMesh) {
  81824. this.poleTargetMesh = options.poleTargetMesh;
  81825. this.poleTargetMesh.computeWorldMatrix(true);
  81826. }
  81827. else if (options.poleTargetBone) {
  81828. this.poleTargetBone = options.poleTargetBone;
  81829. }
  81830. else if (this._bone1.getParent()) {
  81831. this.poleTargetBone = this._bone1.getParent();
  81832. }
  81833. if (options.poleTargetLocalOffset) {
  81834. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  81835. }
  81836. if (options.poleAngle) {
  81837. this.poleAngle = options.poleAngle;
  81838. }
  81839. if (options.bendAxis) {
  81840. this._bendAxis.copyFrom(options.bendAxis);
  81841. }
  81842. if (options.maxAngle) {
  81843. this.maxAngle = options.maxAngle;
  81844. }
  81845. if (options.slerpAmount) {
  81846. this.slerpAmount = options.slerpAmount;
  81847. }
  81848. }
  81849. }
  81850. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  81851. /**
  81852. * Gets or sets maximum allowed angle
  81853. */
  81854. get: function () {
  81855. return this._maxAngle;
  81856. },
  81857. set: function (value) {
  81858. this._setMaxAngle(value);
  81859. },
  81860. enumerable: true,
  81861. configurable: true
  81862. });
  81863. BoneIKController.prototype._setMaxAngle = function (ang) {
  81864. if (ang < 0) {
  81865. ang = 0;
  81866. }
  81867. if (ang > Math.PI || ang == undefined) {
  81868. ang = Math.PI;
  81869. }
  81870. this._maxAngle = ang;
  81871. var a = this._bone1Length;
  81872. var b = this._bone2Length;
  81873. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  81874. };
  81875. /**
  81876. * Force the controller to update the bones
  81877. */
  81878. BoneIKController.prototype.update = function () {
  81879. var bone1 = this._bone1;
  81880. if (!bone1) {
  81881. return;
  81882. }
  81883. var target = this.targetPosition;
  81884. var poleTarget = this.poleTargetPosition;
  81885. var mat1 = BoneIKController._tmpMats[0];
  81886. var mat2 = BoneIKController._tmpMats[1];
  81887. if (this.targetMesh) {
  81888. target.copyFrom(this.targetMesh.getAbsolutePosition());
  81889. }
  81890. if (this.poleTargetBone) {
  81891. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  81892. }
  81893. else if (this.poleTargetMesh) {
  81894. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  81895. }
  81896. var bonePos = BoneIKController._tmpVecs[0];
  81897. var zaxis = BoneIKController._tmpVecs[1];
  81898. var xaxis = BoneIKController._tmpVecs[2];
  81899. var yaxis = BoneIKController._tmpVecs[3];
  81900. var upAxis = BoneIKController._tmpVecs[4];
  81901. var _tmpQuat = BoneIKController._tmpQuat;
  81902. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  81903. poleTarget.subtractToRef(bonePos, upAxis);
  81904. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  81905. upAxis.y = 1;
  81906. }
  81907. else {
  81908. upAxis.normalize();
  81909. }
  81910. target.subtractToRef(bonePos, yaxis);
  81911. yaxis.normalize();
  81912. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  81913. zaxis.normalize();
  81914. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  81915. xaxis.normalize();
  81916. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  81917. var a = this._bone1Length;
  81918. var b = this._bone2Length;
  81919. var c = BABYLON.Vector3.Distance(bonePos, target);
  81920. if (this._maxReach > 0) {
  81921. c = Math.min(this._maxReach, c);
  81922. }
  81923. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  81924. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  81925. if (acosa > 1) {
  81926. acosa = 1;
  81927. }
  81928. if (acosb > 1) {
  81929. acosb = 1;
  81930. }
  81931. if (acosa < -1) {
  81932. acosa = -1;
  81933. }
  81934. if (acosb < -1) {
  81935. acosb = -1;
  81936. }
  81937. var angA = Math.acos(acosa);
  81938. var angB = Math.acos(acosb);
  81939. var angC = -angA - angB;
  81940. if (this._rightHandedSystem) {
  81941. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  81942. mat2.multiplyToRef(mat1, mat1);
  81943. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  81944. mat2.multiplyToRef(mat1, mat1);
  81945. }
  81946. else {
  81947. var _tmpVec = BoneIKController._tmpVecs[5];
  81948. _tmpVec.copyFrom(this._bendAxis);
  81949. _tmpVec.x *= -1;
  81950. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  81951. mat2.multiplyToRef(mat1, mat1);
  81952. }
  81953. if (this.poleAngle) {
  81954. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  81955. mat1.multiplyToRef(mat2, mat1);
  81956. }
  81957. if (this._bone1) {
  81958. if (this.slerpAmount < 1) {
  81959. if (!this._slerping) {
  81960. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  81961. }
  81962. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  81963. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  81964. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  81965. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  81966. this._slerping = true;
  81967. }
  81968. else {
  81969. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  81970. this._bone1Mat.copyFrom(mat1);
  81971. this._slerping = false;
  81972. }
  81973. }
  81974. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  81975. this._bone2Ang = angC;
  81976. };
  81977. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81978. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  81979. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81980. return BoneIKController;
  81981. }());
  81982. BABYLON.BoneIKController = BoneIKController;
  81983. })(BABYLON || (BABYLON = {}));
  81984. //# sourceMappingURL=babylon.boneIKController.js.map
  81985. var BABYLON;
  81986. (function (BABYLON) {
  81987. /**
  81988. * Class used to make a bone look toward a point in space
  81989. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  81990. */
  81991. var BoneLookController = /** @class */ (function () {
  81992. /**
  81993. * Create a BoneLookController
  81994. * @param mesh the mesh that the bone belongs to
  81995. * @param bone the bone that will be looking to the target
  81996. * @param target the target Vector3 to look at
  81997. * @param settings optional settings:
  81998. * * maxYaw: the maximum angle the bone will yaw to
  81999. * * minYaw: the minimum angle the bone will yaw to
  82000. * * maxPitch: the maximum angle the bone will pitch to
  82001. * * minPitch: the minimum angle the bone will yaw to
  82002. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  82003. * * upAxis: the up axis of the coordinate system
  82004. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  82005. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  82006. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  82007. * * adjustYaw: used to make an adjustment to the yaw of the bone
  82008. * * adjustPitch: used to make an adjustment to the pitch of the bone
  82009. * * adjustRoll: used to make an adjustment to the roll of the bone
  82010. **/
  82011. function BoneLookController(mesh, bone, target, options) {
  82012. /**
  82013. * The up axis of the coordinate system that is used when the bone is rotated
  82014. */
  82015. this.upAxis = BABYLON.Vector3.Up();
  82016. /**
  82017. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  82018. */
  82019. this.upAxisSpace = BABYLON.Space.LOCAL;
  82020. /**
  82021. * Used to make an adjustment to the yaw of the bone
  82022. */
  82023. this.adjustYaw = 0;
  82024. /**
  82025. * Used to make an adjustment to the pitch of the bone
  82026. */
  82027. this.adjustPitch = 0;
  82028. /**
  82029. * Used to make an adjustment to the roll of the bone
  82030. */
  82031. this.adjustRoll = 0;
  82032. /**
  82033. * 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)
  82034. */
  82035. this.slerpAmount = 1;
  82036. this._boneQuat = BABYLON.Quaternion.Identity();
  82037. this._slerping = false;
  82038. this._firstFrameSkipped = false;
  82039. this._fowardAxis = BABYLON.Vector3.Forward();
  82040. this.mesh = mesh;
  82041. this.bone = bone;
  82042. this.target = target;
  82043. if (options) {
  82044. if (options.adjustYaw) {
  82045. this.adjustYaw = options.adjustYaw;
  82046. }
  82047. if (options.adjustPitch) {
  82048. this.adjustPitch = options.adjustPitch;
  82049. }
  82050. if (options.adjustRoll) {
  82051. this.adjustRoll = options.adjustRoll;
  82052. }
  82053. if (options.maxYaw != null) {
  82054. this.maxYaw = options.maxYaw;
  82055. }
  82056. else {
  82057. this.maxYaw = Math.PI;
  82058. }
  82059. if (options.minYaw != null) {
  82060. this.minYaw = options.minYaw;
  82061. }
  82062. else {
  82063. this.minYaw = -Math.PI;
  82064. }
  82065. if (options.maxPitch != null) {
  82066. this.maxPitch = options.maxPitch;
  82067. }
  82068. else {
  82069. this.maxPitch = Math.PI;
  82070. }
  82071. if (options.minPitch != null) {
  82072. this.minPitch = options.minPitch;
  82073. }
  82074. else {
  82075. this.minPitch = -Math.PI;
  82076. }
  82077. if (options.slerpAmount != null) {
  82078. this.slerpAmount = options.slerpAmount;
  82079. }
  82080. if (options.upAxis != null) {
  82081. this.upAxis = options.upAxis;
  82082. }
  82083. if (options.upAxisSpace != null) {
  82084. this.upAxisSpace = options.upAxisSpace;
  82085. }
  82086. if (options.yawAxis != null || options.pitchAxis != null) {
  82087. var newYawAxis = BABYLON.Axis.Y;
  82088. var newPitchAxis = BABYLON.Axis.X;
  82089. if (options.yawAxis != null) {
  82090. newYawAxis = options.yawAxis.clone();
  82091. newYawAxis.normalize();
  82092. }
  82093. if (options.pitchAxis != null) {
  82094. newPitchAxis = options.pitchAxis.clone();
  82095. newPitchAxis.normalize();
  82096. }
  82097. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  82098. this._transformYawPitch = BABYLON.Matrix.Identity();
  82099. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  82100. this._transformYawPitchInv = this._transformYawPitch.clone();
  82101. this._transformYawPitch.invert();
  82102. }
  82103. }
  82104. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  82105. this.upAxisSpace = BABYLON.Space.LOCAL;
  82106. }
  82107. }
  82108. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  82109. /**
  82110. * Gets or sets the minimum yaw angle that the bone can look to
  82111. */
  82112. get: function () {
  82113. return this._minYaw;
  82114. },
  82115. set: function (value) {
  82116. this._minYaw = value;
  82117. this._minYawSin = Math.sin(value);
  82118. this._minYawCos = Math.cos(value);
  82119. if (this._maxYaw != null) {
  82120. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82121. this._yawRange = this._maxYaw - this._minYaw;
  82122. }
  82123. },
  82124. enumerable: true,
  82125. configurable: true
  82126. });
  82127. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  82128. /**
  82129. * Gets or sets the maximum yaw angle that the bone can look to
  82130. */
  82131. get: function () {
  82132. return this._maxYaw;
  82133. },
  82134. set: function (value) {
  82135. this._maxYaw = value;
  82136. this._maxYawSin = Math.sin(value);
  82137. this._maxYawCos = Math.cos(value);
  82138. if (this._minYaw != null) {
  82139. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82140. this._yawRange = this._maxYaw - this._minYaw;
  82141. }
  82142. },
  82143. enumerable: true,
  82144. configurable: true
  82145. });
  82146. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  82147. /**
  82148. * Gets or sets the minimum pitch angle that the bone can look to
  82149. */
  82150. get: function () {
  82151. return this._minPitch;
  82152. },
  82153. set: function (value) {
  82154. this._minPitch = value;
  82155. this._minPitchTan = Math.tan(value);
  82156. },
  82157. enumerable: true,
  82158. configurable: true
  82159. });
  82160. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  82161. /**
  82162. * Gets or sets the maximum pitch angle that the bone can look to
  82163. */
  82164. get: function () {
  82165. return this._maxPitch;
  82166. },
  82167. set: function (value) {
  82168. this._maxPitch = value;
  82169. this._maxPitchTan = Math.tan(value);
  82170. },
  82171. enumerable: true,
  82172. configurable: true
  82173. });
  82174. /**
  82175. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  82176. */
  82177. BoneLookController.prototype.update = function () {
  82178. //skip the first frame when slerping so that the mesh rotation is correct
  82179. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  82180. this._firstFrameSkipped = true;
  82181. return;
  82182. }
  82183. var bone = this.bone;
  82184. var bonePos = BoneLookController._tmpVecs[0];
  82185. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  82186. var target = this.target;
  82187. var _tmpMat1 = BoneLookController._tmpMats[0];
  82188. var _tmpMat2 = BoneLookController._tmpMats[1];
  82189. var mesh = this.mesh;
  82190. var parentBone = bone.getParent();
  82191. var upAxis = BoneLookController._tmpVecs[1];
  82192. upAxis.copyFrom(this.upAxis);
  82193. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  82194. if (this._transformYawPitch) {
  82195. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  82196. }
  82197. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  82198. }
  82199. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  82200. mesh.getDirectionToRef(upAxis, upAxis);
  82201. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  82202. upAxis.normalize();
  82203. }
  82204. }
  82205. var checkYaw = false;
  82206. var checkPitch = false;
  82207. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  82208. checkYaw = true;
  82209. }
  82210. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  82211. checkPitch = true;
  82212. }
  82213. if (checkYaw || checkPitch) {
  82214. var spaceMat = BoneLookController._tmpMats[2];
  82215. var spaceMatInv = BoneLookController._tmpMats[3];
  82216. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  82217. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  82218. }
  82219. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  82220. spaceMat.copyFrom(mesh.getWorldMatrix());
  82221. }
  82222. else {
  82223. var forwardAxis = BoneLookController._tmpVecs[2];
  82224. forwardAxis.copyFrom(this._fowardAxis);
  82225. if (this._transformYawPitch) {
  82226. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  82227. }
  82228. if (parentBone) {
  82229. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  82230. }
  82231. else {
  82232. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  82233. }
  82234. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  82235. rightAxis.normalize();
  82236. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  82237. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  82238. }
  82239. spaceMat.invertToRef(spaceMatInv);
  82240. var xzlen = null;
  82241. if (checkPitch) {
  82242. var localTarget = BoneLookController._tmpVecs[3];
  82243. target.subtractToRef(bonePos, localTarget);
  82244. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82245. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82246. var pitch = Math.atan2(localTarget.y, xzlen);
  82247. var newPitch = pitch;
  82248. if (pitch > this._maxPitch) {
  82249. localTarget.y = this._maxPitchTan * xzlen;
  82250. newPitch = this._maxPitch;
  82251. }
  82252. else if (pitch < this._minPitch) {
  82253. localTarget.y = this._minPitchTan * xzlen;
  82254. newPitch = this._minPitch;
  82255. }
  82256. if (pitch != newPitch) {
  82257. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82258. localTarget.addInPlace(bonePos);
  82259. target = localTarget;
  82260. }
  82261. }
  82262. if (checkYaw) {
  82263. var localTarget = BoneLookController._tmpVecs[4];
  82264. target.subtractToRef(bonePos, localTarget);
  82265. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82266. var yaw = Math.atan2(localTarget.x, localTarget.z);
  82267. var newYaw = yaw;
  82268. if (yaw > this._maxYaw || yaw < this._minYaw) {
  82269. if (xzlen == null) {
  82270. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82271. }
  82272. if (this._yawRange > Math.PI) {
  82273. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  82274. localTarget.z = this._maxYawCos * xzlen;
  82275. localTarget.x = this._maxYawSin * xzlen;
  82276. newYaw = this._maxYaw;
  82277. }
  82278. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  82279. localTarget.z = this._minYawCos * xzlen;
  82280. localTarget.x = this._minYawSin * xzlen;
  82281. newYaw = this._minYaw;
  82282. }
  82283. }
  82284. else {
  82285. if (yaw > this._maxYaw) {
  82286. localTarget.z = this._maxYawCos * xzlen;
  82287. localTarget.x = this._maxYawSin * xzlen;
  82288. newYaw = this._maxYaw;
  82289. }
  82290. else if (yaw < this._minYaw) {
  82291. localTarget.z = this._minYawCos * xzlen;
  82292. localTarget.x = this._minYawSin * xzlen;
  82293. newYaw = this._minYaw;
  82294. }
  82295. }
  82296. }
  82297. if (this._slerping && this._yawRange > Math.PI) {
  82298. //are we going to be crossing into the min/max region?
  82299. var boneFwd = BoneLookController._tmpVecs[8];
  82300. boneFwd.copyFrom(BABYLON.Axis.Z);
  82301. if (this._transformYawPitch) {
  82302. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  82303. }
  82304. var boneRotMat = BoneLookController._tmpMats[4];
  82305. this._boneQuat.toRotationMatrix(boneRotMat);
  82306. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  82307. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  82308. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  82309. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  82310. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  82311. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  82312. if (angBtwTar > angBtwMidYaw) {
  82313. if (xzlen == null) {
  82314. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82315. }
  82316. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  82317. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  82318. if (angBtwMin < angBtwMax) {
  82319. newYaw = boneYaw + Math.PI * .75;
  82320. localTarget.z = Math.cos(newYaw) * xzlen;
  82321. localTarget.x = Math.sin(newYaw) * xzlen;
  82322. }
  82323. else {
  82324. newYaw = boneYaw - Math.PI * .75;
  82325. localTarget.z = Math.cos(newYaw) * xzlen;
  82326. localTarget.x = Math.sin(newYaw) * xzlen;
  82327. }
  82328. }
  82329. }
  82330. if (yaw != newYaw) {
  82331. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82332. localTarget.addInPlace(bonePos);
  82333. target = localTarget;
  82334. }
  82335. }
  82336. }
  82337. var zaxis = BoneLookController._tmpVecs[5];
  82338. var xaxis = BoneLookController._tmpVecs[6];
  82339. var yaxis = BoneLookController._tmpVecs[7];
  82340. var _tmpQuat = BoneLookController._tmpQuat;
  82341. target.subtractToRef(bonePos, zaxis);
  82342. zaxis.normalize();
  82343. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  82344. xaxis.normalize();
  82345. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  82346. yaxis.normalize();
  82347. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  82348. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  82349. return;
  82350. }
  82351. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  82352. return;
  82353. }
  82354. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  82355. return;
  82356. }
  82357. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  82358. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  82359. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  82360. }
  82361. if (this.slerpAmount < 1) {
  82362. if (!this._slerping) {
  82363. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  82364. }
  82365. if (this._transformYawPitch) {
  82366. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82367. }
  82368. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  82369. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  82370. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  82371. this._slerping = true;
  82372. }
  82373. else {
  82374. if (this._transformYawPitch) {
  82375. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82376. }
  82377. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  82378. this._slerping = false;
  82379. }
  82380. };
  82381. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  82382. var angDiff = ang2 - ang1;
  82383. angDiff %= Math.PI * 2;
  82384. if (angDiff > Math.PI) {
  82385. angDiff -= Math.PI * 2;
  82386. }
  82387. else if (angDiff < -Math.PI) {
  82388. angDiff += Math.PI * 2;
  82389. }
  82390. return angDiff;
  82391. };
  82392. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  82393. ang1 %= (2 * Math.PI);
  82394. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82395. ang2 %= (2 * Math.PI);
  82396. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82397. var ab = 0;
  82398. if (ang1 < ang2) {
  82399. ab = ang2 - ang1;
  82400. }
  82401. else {
  82402. ab = ang1 - ang2;
  82403. }
  82404. if (ab > Math.PI) {
  82405. ab = Math.PI * 2 - ab;
  82406. }
  82407. return ab;
  82408. };
  82409. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  82410. ang %= (2 * Math.PI);
  82411. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  82412. ang1 %= (2 * Math.PI);
  82413. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82414. ang2 %= (2 * Math.PI);
  82415. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82416. if (ang1 < ang2) {
  82417. if (ang > ang1 && ang < ang2) {
  82418. return true;
  82419. }
  82420. }
  82421. else {
  82422. if (ang > ang2 && ang < ang1) {
  82423. return true;
  82424. }
  82425. }
  82426. return false;
  82427. };
  82428. 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()];
  82429. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  82430. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82431. return BoneLookController;
  82432. }());
  82433. BABYLON.BoneLookController = BoneLookController;
  82434. })(BABYLON || (BABYLON = {}));
  82435. //# sourceMappingURL=babylon.boneLookController.js.map
  82436. var BABYLON;
  82437. (function (BABYLON) {
  82438. /**
  82439. * Class used to handle skinning animations
  82440. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82441. */
  82442. var Skeleton = /** @class */ (function () {
  82443. /**
  82444. * Creates a new skeleton
  82445. * @param name defines the skeleton name
  82446. * @param id defines the skeleton Id
  82447. * @param scene defines the hosting scene
  82448. */
  82449. function Skeleton(
  82450. /** defines the skeleton name */
  82451. name,
  82452. /** defines the skeleton Id */
  82453. id, scene) {
  82454. this.name = name;
  82455. this.id = id;
  82456. /**
  82457. * Gets the list of child bones
  82458. */
  82459. this.bones = new Array();
  82460. /**
  82461. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  82462. */
  82463. this.needInitialSkinMatrix = false;
  82464. this._isDirty = true;
  82465. this._meshesWithPoseMatrix = new Array();
  82466. this._identity = BABYLON.Matrix.Identity();
  82467. this._ranges = {};
  82468. this._lastAbsoluteTransformsUpdateId = -1;
  82469. /**
  82470. * Specifies if the skeleton should be serialized
  82471. */
  82472. this.doNotSerialize = false;
  82473. this._animationPropertiesOverride = null;
  82474. // Events
  82475. /**
  82476. * An observable triggered before computing the skeleton's matrices
  82477. */
  82478. this.onBeforeComputeObservable = new BABYLON.Observable();
  82479. this.bones = [];
  82480. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82481. scene.skeletons.push(this);
  82482. //make sure it will recalculate the matrix next time prepare is called.
  82483. this._isDirty = true;
  82484. }
  82485. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  82486. /**
  82487. * Gets or sets the animation properties override
  82488. */
  82489. get: function () {
  82490. if (!this._animationPropertiesOverride) {
  82491. return this._scene.animationPropertiesOverride;
  82492. }
  82493. return this._animationPropertiesOverride;
  82494. },
  82495. set: function (value) {
  82496. this._animationPropertiesOverride = value;
  82497. },
  82498. enumerable: true,
  82499. configurable: true
  82500. });
  82501. // Members
  82502. /**
  82503. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  82504. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  82505. * @returns a Float32Array containing matrices data
  82506. */
  82507. Skeleton.prototype.getTransformMatrices = function (mesh) {
  82508. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  82509. return mesh._bonesTransformMatrices;
  82510. }
  82511. if (!this._transformMatrices) {
  82512. this.prepare();
  82513. }
  82514. return this._transformMatrices;
  82515. };
  82516. /**
  82517. * Gets the current hosting scene
  82518. * @returns a scene object
  82519. */
  82520. Skeleton.prototype.getScene = function () {
  82521. return this._scene;
  82522. };
  82523. // Methods
  82524. /**
  82525. * Gets a string representing the current skeleton data
  82526. * @param fullDetails defines a boolean indicating if we want a verbose version
  82527. * @returns a string representing the current skeleton data
  82528. */
  82529. Skeleton.prototype.toString = function (fullDetails) {
  82530. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  82531. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  82532. if (fullDetails) {
  82533. ret += ", Ranges: {";
  82534. var first = true;
  82535. for (var name_1 in this._ranges) {
  82536. if (first) {
  82537. ret += ", ";
  82538. first = false;
  82539. }
  82540. ret += name_1;
  82541. }
  82542. ret += "}";
  82543. }
  82544. return ret;
  82545. };
  82546. /**
  82547. * Get bone's index searching by name
  82548. * @param name defines bone's name to search for
  82549. * @return the indice of the bone. Returns -1 if not found
  82550. */
  82551. Skeleton.prototype.getBoneIndexByName = function (name) {
  82552. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  82553. if (this.bones[boneIndex].name === name) {
  82554. return boneIndex;
  82555. }
  82556. }
  82557. return -1;
  82558. };
  82559. /**
  82560. * Creater a new animation range
  82561. * @param name defines the name of the range
  82562. * @param from defines the start key
  82563. * @param to defines the end key
  82564. */
  82565. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  82566. // check name not already in use
  82567. if (!this._ranges[name]) {
  82568. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  82569. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82570. if (this.bones[i].animations[0]) {
  82571. this.bones[i].animations[0].createRange(name, from, to);
  82572. }
  82573. }
  82574. }
  82575. };
  82576. /**
  82577. * Delete a specific animation range
  82578. * @param name defines the name of the range
  82579. * @param deleteFrames defines if frames must be removed as well
  82580. */
  82581. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  82582. if (deleteFrames === void 0) { deleteFrames = true; }
  82583. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82584. if (this.bones[i].animations[0]) {
  82585. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  82586. }
  82587. }
  82588. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  82589. };
  82590. /**
  82591. * Gets a specific animation range
  82592. * @param name defines the name of the range to look for
  82593. * @returns the requested animation range or null if not found
  82594. */
  82595. Skeleton.prototype.getAnimationRange = function (name) {
  82596. return this._ranges[name];
  82597. };
  82598. /**
  82599. * Gets the list of all animation ranges defined on this skeleton
  82600. * @returns an array
  82601. */
  82602. Skeleton.prototype.getAnimationRanges = function () {
  82603. var animationRanges = [];
  82604. var name;
  82605. var i = 0;
  82606. for (name in this._ranges) {
  82607. animationRanges[i] = this._ranges[name];
  82608. i++;
  82609. }
  82610. return animationRanges;
  82611. };
  82612. /**
  82613. * Copy animation range from a source skeleton.
  82614. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  82615. * @param source defines the source skeleton
  82616. * @param name defines the name of the range to copy
  82617. * @param rescaleAsRequired defines if rescaling must be applied if required
  82618. * @returns true if operation was successful
  82619. */
  82620. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  82621. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  82622. if (this._ranges[name] || !source.getAnimationRange(name)) {
  82623. return false;
  82624. }
  82625. var ret = true;
  82626. var frameOffset = this._getHighestAnimationFrame() + 1;
  82627. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  82628. var boneDict = {};
  82629. var sourceBones = source.bones;
  82630. var nBones;
  82631. var i;
  82632. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  82633. boneDict[sourceBones[i].name] = sourceBones[i];
  82634. }
  82635. if (this.bones.length !== sourceBones.length) {
  82636. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  82637. ret = false;
  82638. }
  82639. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  82640. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  82641. var boneName = this.bones[i].name;
  82642. var sourceBone = boneDict[boneName];
  82643. if (sourceBone) {
  82644. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  82645. }
  82646. else {
  82647. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  82648. ret = false;
  82649. }
  82650. }
  82651. // do not call createAnimationRange(), since it also is done to bones, which was already done
  82652. var range = source.getAnimationRange(name);
  82653. if (range) {
  82654. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  82655. }
  82656. return ret;
  82657. };
  82658. /**
  82659. * Forces the skeleton to go to rest pose
  82660. */
  82661. Skeleton.prototype.returnToRest = function () {
  82662. for (var index = 0; index < this.bones.length; index++) {
  82663. this.bones[index].returnToRest();
  82664. }
  82665. };
  82666. Skeleton.prototype._getHighestAnimationFrame = function () {
  82667. var ret = 0;
  82668. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82669. if (this.bones[i].animations[0]) {
  82670. var highest = this.bones[i].animations[0].getHighestFrame();
  82671. if (ret < highest) {
  82672. ret = highest;
  82673. }
  82674. }
  82675. }
  82676. return ret;
  82677. };
  82678. /**
  82679. * Begin a specific animation range
  82680. * @param name defines the name of the range to start
  82681. * @param loop defines if looping must be turned on (false by default)
  82682. * @param speedRatio defines the speed ratio to apply (1 by default)
  82683. * @param onAnimationEnd defines a callback which will be called when animation will end
  82684. * @returns a new animatable
  82685. */
  82686. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  82687. var range = this.getAnimationRange(name);
  82688. if (!range) {
  82689. return null;
  82690. }
  82691. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  82692. };
  82693. /** @hidden */
  82694. Skeleton.prototype._markAsDirty = function () {
  82695. this._isDirty = true;
  82696. };
  82697. /** @hidden */
  82698. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  82699. this._meshesWithPoseMatrix.push(mesh);
  82700. };
  82701. /** @hidden */
  82702. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  82703. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  82704. if (index > -1) {
  82705. this._meshesWithPoseMatrix.splice(index, 1);
  82706. }
  82707. };
  82708. /** @hidden */
  82709. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  82710. this.onBeforeComputeObservable.notifyObservers(this);
  82711. for (var index = 0; index < this.bones.length; index++) {
  82712. var bone = this.bones[index];
  82713. var parentBone = bone.getParent();
  82714. if (parentBone) {
  82715. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  82716. }
  82717. else {
  82718. if (initialSkinMatrix) {
  82719. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  82720. }
  82721. else {
  82722. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  82723. }
  82724. }
  82725. if (bone._index !== -1) {
  82726. var mappedIndex = bone._index === null ? index : bone._index;
  82727. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  82728. }
  82729. }
  82730. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  82731. };
  82732. /**
  82733. * Build all resources required to render a skeleton
  82734. */
  82735. Skeleton.prototype.prepare = function () {
  82736. if (!this._isDirty) {
  82737. return;
  82738. }
  82739. if (this.needInitialSkinMatrix) {
  82740. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  82741. var mesh = this._meshesWithPoseMatrix[index];
  82742. var poseMatrix = mesh.getPoseMatrix();
  82743. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  82744. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82745. }
  82746. if (this._synchronizedWithMesh !== mesh) {
  82747. this._synchronizedWithMesh = mesh;
  82748. // Prepare bones
  82749. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  82750. var bone = this.bones[boneIndex];
  82751. if (!bone.getParent()) {
  82752. var matrix = bone.getBaseMatrix();
  82753. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  82754. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  82755. }
  82756. }
  82757. }
  82758. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  82759. }
  82760. }
  82761. else {
  82762. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  82763. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82764. }
  82765. this._computeTransformMatrices(this._transformMatrices, null);
  82766. }
  82767. this._isDirty = false;
  82768. this._scene._activeBones.addCount(this.bones.length, false);
  82769. };
  82770. /**
  82771. * Gets the list of animatables currently running for this skeleton
  82772. * @returns an array of animatables
  82773. */
  82774. Skeleton.prototype.getAnimatables = function () {
  82775. if (!this._animatables || this._animatables.length !== this.bones.length) {
  82776. this._animatables = [];
  82777. for (var index = 0; index < this.bones.length; index++) {
  82778. this._animatables.push(this.bones[index]);
  82779. }
  82780. }
  82781. return this._animatables;
  82782. };
  82783. /**
  82784. * Clone the current skeleton
  82785. * @param name defines the name of the new skeleton
  82786. * @param id defines the id of the enw skeleton
  82787. * @returns the new skeleton
  82788. */
  82789. Skeleton.prototype.clone = function (name, id) {
  82790. var result = new Skeleton(name, id || name, this._scene);
  82791. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82792. for (var index = 0; index < this.bones.length; index++) {
  82793. var source = this.bones[index];
  82794. var parentBone = null;
  82795. var parent_1 = source.getParent();
  82796. if (parent_1) {
  82797. var parentIndex = this.bones.indexOf(parent_1);
  82798. parentBone = result.bones[parentIndex];
  82799. }
  82800. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  82801. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  82802. }
  82803. if (this._ranges) {
  82804. result._ranges = {};
  82805. for (var rangeName in this._ranges) {
  82806. var range = this._ranges[rangeName];
  82807. if (range) {
  82808. result._ranges[rangeName] = range.clone();
  82809. }
  82810. }
  82811. }
  82812. this._isDirty = true;
  82813. return result;
  82814. };
  82815. /**
  82816. * Enable animation blending for this skeleton
  82817. * @param blendingSpeed defines the blending speed to apply
  82818. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  82819. */
  82820. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  82821. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  82822. this.bones.forEach(function (bone) {
  82823. bone.animations.forEach(function (animation) {
  82824. animation.enableBlending = true;
  82825. animation.blendingSpeed = blendingSpeed;
  82826. });
  82827. });
  82828. };
  82829. /**
  82830. * Releases all resources associated with the current skeleton
  82831. */
  82832. Skeleton.prototype.dispose = function () {
  82833. this._meshesWithPoseMatrix = [];
  82834. // Animations
  82835. this.getScene().stopAnimation(this);
  82836. // Remove from scene
  82837. this.getScene().removeSkeleton(this);
  82838. };
  82839. /**
  82840. * Serialize the skeleton in a JSON object
  82841. * @returns a JSON object
  82842. */
  82843. Skeleton.prototype.serialize = function () {
  82844. var serializationObject = {};
  82845. serializationObject.name = this.name;
  82846. serializationObject.id = this.id;
  82847. if (this.dimensionsAtRest) {
  82848. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  82849. }
  82850. serializationObject.bones = [];
  82851. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82852. for (var index = 0; index < this.bones.length; index++) {
  82853. var bone = this.bones[index];
  82854. var parent_2 = bone.getParent();
  82855. var serializedBone = {
  82856. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  82857. name: bone.name,
  82858. matrix: bone.getBaseMatrix().toArray(),
  82859. rest: bone.getRestPose().toArray()
  82860. };
  82861. serializationObject.bones.push(serializedBone);
  82862. if (bone.length) {
  82863. serializedBone.length = bone.length;
  82864. }
  82865. if (bone.metadata) {
  82866. serializedBone.metadata = bone.metadata;
  82867. }
  82868. if (bone.animations && bone.animations.length > 0) {
  82869. serializedBone.animation = bone.animations[0].serialize();
  82870. }
  82871. serializationObject.ranges = [];
  82872. for (var name in this._ranges) {
  82873. var source = this._ranges[name];
  82874. if (!source) {
  82875. continue;
  82876. }
  82877. var range = {};
  82878. range.name = name;
  82879. range.from = source.from;
  82880. range.to = source.to;
  82881. serializationObject.ranges.push(range);
  82882. }
  82883. }
  82884. return serializationObject;
  82885. };
  82886. /**
  82887. * Creates a new skeleton from serialized data
  82888. * @param parsedSkeleton defines the serialized data
  82889. * @param scene defines the hosting scene
  82890. * @returns a new skeleton
  82891. */
  82892. Skeleton.Parse = function (parsedSkeleton, scene) {
  82893. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  82894. if (parsedSkeleton.dimensionsAtRest) {
  82895. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  82896. }
  82897. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  82898. var index;
  82899. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  82900. var parsedBone = parsedSkeleton.bones[index];
  82901. var parentBone = null;
  82902. if (parsedBone.parentBoneIndex > -1) {
  82903. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  82904. }
  82905. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  82906. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  82907. if (parsedBone.length) {
  82908. bone.length = parsedBone.length;
  82909. }
  82910. if (parsedBone.metadata) {
  82911. bone.metadata = parsedBone.metadata;
  82912. }
  82913. if (parsedBone.animation) {
  82914. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  82915. }
  82916. }
  82917. // placed after bones, so createAnimationRange can cascade down
  82918. if (parsedSkeleton.ranges) {
  82919. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  82920. var data = parsedSkeleton.ranges[index];
  82921. skeleton.createAnimationRange(data.name, data.from, data.to);
  82922. }
  82923. }
  82924. return skeleton;
  82925. };
  82926. /**
  82927. * Compute all node absolute transforms
  82928. * @param forceUpdate defines if computation must be done even if cache is up to date
  82929. */
  82930. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  82931. if (forceUpdate === void 0) { forceUpdate = false; }
  82932. var renderId = this._scene.getRenderId();
  82933. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  82934. this.bones[0].computeAbsoluteTransforms();
  82935. this._lastAbsoluteTransformsUpdateId = renderId;
  82936. }
  82937. };
  82938. /**
  82939. * Gets the root pose matrix
  82940. * @returns a matrix
  82941. */
  82942. Skeleton.prototype.getPoseMatrix = function () {
  82943. var poseMatrix = null;
  82944. if (this._meshesWithPoseMatrix.length > 0) {
  82945. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  82946. }
  82947. return poseMatrix;
  82948. };
  82949. /**
  82950. * Sorts bones per internal index
  82951. */
  82952. Skeleton.prototype.sortBones = function () {
  82953. var bones = new Array();
  82954. var visited = new Array(this.bones.length);
  82955. for (var index = 0; index < this.bones.length; index++) {
  82956. this._sortBones(index, bones, visited);
  82957. }
  82958. this.bones = bones;
  82959. };
  82960. Skeleton.prototype._sortBones = function (index, bones, visited) {
  82961. if (visited[index]) {
  82962. return;
  82963. }
  82964. visited[index] = true;
  82965. var bone = this.bones[index];
  82966. if (bone._index === undefined) {
  82967. bone._index = index;
  82968. }
  82969. var parentBone = bone.getParent();
  82970. if (parentBone) {
  82971. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  82972. }
  82973. bones.push(bone);
  82974. };
  82975. return Skeleton;
  82976. }());
  82977. BABYLON.Skeleton = Skeleton;
  82978. })(BABYLON || (BABYLON = {}));
  82979. //# sourceMappingURL=babylon.skeleton.js.map
  82980. var BABYLON;
  82981. (function (BABYLON) {
  82982. ;
  82983. /**
  82984. * This groups tools to convert HDR texture to native colors array.
  82985. */
  82986. var HDRTools = /** @class */ (function () {
  82987. function HDRTools() {
  82988. }
  82989. HDRTools.Ldexp = function (mantissa, exponent) {
  82990. if (exponent > 1023) {
  82991. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  82992. }
  82993. if (exponent < -1074) {
  82994. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  82995. }
  82996. return mantissa * Math.pow(2, exponent);
  82997. };
  82998. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  82999. if (exponent > 0) { /*nonzero pixel*/
  83000. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  83001. float32array[index + 0] = red * exponent;
  83002. float32array[index + 1] = green * exponent;
  83003. float32array[index + 2] = blue * exponent;
  83004. }
  83005. else {
  83006. float32array[index + 0] = 0;
  83007. float32array[index + 1] = 0;
  83008. float32array[index + 2] = 0;
  83009. }
  83010. };
  83011. HDRTools.readStringLine = function (uint8array, startIndex) {
  83012. var line = "";
  83013. var character = "";
  83014. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  83015. character = String.fromCharCode(uint8array[i]);
  83016. if (character == "\n") {
  83017. break;
  83018. }
  83019. line += character;
  83020. }
  83021. return line;
  83022. };
  83023. /**
  83024. * Reads header information from an RGBE texture stored in a native array.
  83025. * More information on this format are available here:
  83026. * https://en.wikipedia.org/wiki/RGBE_image_format
  83027. *
  83028. * @param uint8array The binary file stored in native array.
  83029. * @return The header information.
  83030. */
  83031. HDRTools.RGBE_ReadHeader = function (uint8array) {
  83032. var height = 0;
  83033. var width = 0;
  83034. var line = this.readStringLine(uint8array, 0);
  83035. if (line[0] != '#' || line[1] != '?') {
  83036. throw "Bad HDR Format.";
  83037. }
  83038. var endOfHeader = false;
  83039. var findFormat = false;
  83040. var lineIndex = 0;
  83041. do {
  83042. lineIndex += (line.length + 1);
  83043. line = this.readStringLine(uint8array, lineIndex);
  83044. if (line == "FORMAT=32-bit_rle_rgbe") {
  83045. findFormat = true;
  83046. }
  83047. else if (line.length == 0) {
  83048. endOfHeader = true;
  83049. }
  83050. } while (!endOfHeader);
  83051. if (!findFormat) {
  83052. throw "HDR Bad header format, unsupported FORMAT";
  83053. }
  83054. lineIndex += (line.length + 1);
  83055. line = this.readStringLine(uint8array, lineIndex);
  83056. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  83057. var match = sizeRegexp.exec(line);
  83058. // TODO. Support +Y and -X if needed.
  83059. if (!match || match.length < 3) {
  83060. throw "HDR Bad header format, no size";
  83061. }
  83062. width = parseInt(match[2]);
  83063. height = parseInt(match[1]);
  83064. if (width < 8 || width > 0x7fff) {
  83065. throw "HDR Bad header format, unsupported size";
  83066. }
  83067. lineIndex += (line.length + 1);
  83068. return {
  83069. height: height,
  83070. width: width,
  83071. dataPosition: lineIndex
  83072. };
  83073. };
  83074. /**
  83075. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  83076. * This RGBE texture needs to store the information as a panorama.
  83077. *
  83078. * More information on this format are available here:
  83079. * https://en.wikipedia.org/wiki/RGBE_image_format
  83080. *
  83081. * @param buffer The binary file stored in an array buffer.
  83082. * @param size The expected size of the extracted cubemap.
  83083. * @return The Cube Map information.
  83084. */
  83085. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  83086. var uint8array = new Uint8Array(buffer);
  83087. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  83088. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83089. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  83090. return cubeMapData;
  83091. };
  83092. /**
  83093. * Returns the pixels data extracted from an RGBE texture.
  83094. * This pixels will be stored left to right up to down in the R G B order in one array.
  83095. *
  83096. * More information on this format are available here:
  83097. * https://en.wikipedia.org/wiki/RGBE_image_format
  83098. *
  83099. * @param uint8array The binary file stored in an array buffer.
  83100. * @param hdrInfo The header information of the file.
  83101. * @return The pixels data in RGB right to left up to down order.
  83102. */
  83103. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  83104. // Keep for multi format supports.
  83105. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83106. };
  83107. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  83108. var num_scanlines = hdrInfo.height;
  83109. var scanline_width = hdrInfo.width;
  83110. var a, b, c, d, count;
  83111. var dataIndex = hdrInfo.dataPosition;
  83112. var index = 0, endIndex = 0, i = 0;
  83113. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  83114. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  83115. // 3 channels of 4 bytes per pixel in float.
  83116. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  83117. var resultArray = new Float32Array(resultBuffer);
  83118. // read in each successive scanline
  83119. while (num_scanlines > 0) {
  83120. a = uint8array[dataIndex++];
  83121. b = uint8array[dataIndex++];
  83122. c = uint8array[dataIndex++];
  83123. d = uint8array[dataIndex++];
  83124. if (a != 2 || b != 2 || (c & 0x80)) {
  83125. // this file is not run length encoded
  83126. throw "HDR Bad header format, not RLE";
  83127. }
  83128. if (((c << 8) | d) != scanline_width) {
  83129. throw "HDR Bad header format, wrong scan line width";
  83130. }
  83131. index = 0;
  83132. // read each of the four channels for the scanline into the buffer
  83133. for (i = 0; i < 4; i++) {
  83134. endIndex = (i + 1) * scanline_width;
  83135. while (index < endIndex) {
  83136. a = uint8array[dataIndex++];
  83137. b = uint8array[dataIndex++];
  83138. if (a > 128) {
  83139. // a run of the same value
  83140. count = a - 128;
  83141. if ((count == 0) || (count > endIndex - index)) {
  83142. throw "HDR Bad Format, bad scanline data (run)";
  83143. }
  83144. while (count-- > 0) {
  83145. scanLineArray[index++] = b;
  83146. }
  83147. }
  83148. else {
  83149. // a non-run
  83150. count = a;
  83151. if ((count == 0) || (count > endIndex - index)) {
  83152. throw "HDR Bad Format, bad scanline data (non-run)";
  83153. }
  83154. scanLineArray[index++] = b;
  83155. if (--count > 0) {
  83156. for (var j = 0; j < count; j++) {
  83157. scanLineArray[index++] = uint8array[dataIndex++];
  83158. }
  83159. }
  83160. }
  83161. }
  83162. }
  83163. // now convert data from buffer into floats
  83164. for (i = 0; i < scanline_width; i++) {
  83165. a = scanLineArray[i];
  83166. b = scanLineArray[i + scanline_width];
  83167. c = scanLineArray[i + 2 * scanline_width];
  83168. d = scanLineArray[i + 3 * scanline_width];
  83169. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  83170. }
  83171. num_scanlines--;
  83172. }
  83173. return resultArray;
  83174. };
  83175. return HDRTools;
  83176. }());
  83177. BABYLON.HDRTools = HDRTools;
  83178. })(BABYLON || (BABYLON = {}));
  83179. //# sourceMappingURL=babylon.hdr.js.map
  83180. var BABYLON;
  83181. (function (BABYLON) {
  83182. /**
  83183. * This represents a texture coming from an HDR input.
  83184. *
  83185. * The only supported format is currently panorama picture stored in RGBE format.
  83186. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83187. */
  83188. var HDRCubeTexture = /** @class */ (function (_super) {
  83189. __extends(HDRCubeTexture, _super);
  83190. /**
  83191. * Instantiates an HDRTexture from the following parameters.
  83192. *
  83193. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83194. * @param scene The scene the texture will be used in
  83195. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83196. * @param noMipmap Forces to not generate the mipmap if true
  83197. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83198. * @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)
  83199. * @param reserved Reserved flag for internal use.
  83200. */
  83201. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83202. if (noMipmap === void 0) { noMipmap = false; }
  83203. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83204. if (gammaSpace === void 0) { gammaSpace = false; }
  83205. if (reserved === void 0) { reserved = false; }
  83206. if (onLoad === void 0) { onLoad = null; }
  83207. if (onError === void 0) { onError = null; }
  83208. var _this = _super.call(this, scene) || this;
  83209. _this._generateHarmonics = true;
  83210. _this._onLoad = null;
  83211. _this._onError = null;
  83212. /**
  83213. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83214. */
  83215. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83216. _this._isBlocking = true;
  83217. _this._rotationY = 0;
  83218. /**
  83219. * Gets or sets the center of the bounding box associated with the cube texture
  83220. * It must define where the camera used to render the texture was set
  83221. */
  83222. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83223. if (!url) {
  83224. return _this;
  83225. }
  83226. _this.name = url;
  83227. _this.url = url;
  83228. _this.hasAlpha = false;
  83229. _this.isCube = true;
  83230. _this._textureMatrix = BABYLON.Matrix.Identity();
  83231. _this._onLoad = onLoad;
  83232. _this._onError = onError;
  83233. _this.gammaSpace = gammaSpace;
  83234. _this._noMipmap = noMipmap;
  83235. _this._size = size;
  83236. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83237. if (!_this._texture) {
  83238. if (!scene.useDelayedTextureLoading) {
  83239. _this.loadTexture();
  83240. }
  83241. else {
  83242. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83243. }
  83244. }
  83245. return _this;
  83246. }
  83247. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83248. /**
  83249. * Gets wether or not the texture is blocking during loading.
  83250. */
  83251. get: function () {
  83252. return this._isBlocking;
  83253. },
  83254. /**
  83255. * Sets wether or not the texture is blocking during loading.
  83256. */
  83257. set: function (value) {
  83258. this._isBlocking = value;
  83259. },
  83260. enumerable: true,
  83261. configurable: true
  83262. });
  83263. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83264. /**
  83265. * Gets texture matrix rotation angle around Y axis radians.
  83266. */
  83267. get: function () {
  83268. return this._rotationY;
  83269. },
  83270. /**
  83271. * Sets texture matrix rotation angle around Y axis in radians.
  83272. */
  83273. set: function (value) {
  83274. this._rotationY = value;
  83275. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83276. },
  83277. enumerable: true,
  83278. configurable: true
  83279. });
  83280. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83281. get: function () {
  83282. return this._boundingBoxSize;
  83283. },
  83284. /**
  83285. * Gets or sets the size of the bounding box associated with the cube texture
  83286. * When defined, the cubemap will switch to local mode
  83287. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83288. * @example https://www.babylonjs-playground.com/#RNASML
  83289. */
  83290. set: function (value) {
  83291. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83292. return;
  83293. }
  83294. this._boundingBoxSize = value;
  83295. var scene = this.getScene();
  83296. if (scene) {
  83297. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83298. }
  83299. },
  83300. enumerable: true,
  83301. configurable: true
  83302. });
  83303. /**
  83304. * Occurs when the file is raw .hdr file.
  83305. */
  83306. HDRCubeTexture.prototype.loadTexture = function () {
  83307. var _this = this;
  83308. var callback = function (buffer) {
  83309. _this.lodGenerationOffset = 0.0;
  83310. _this.lodGenerationScale = 0.8;
  83311. var scene = _this.getScene();
  83312. if (!scene) {
  83313. return null;
  83314. }
  83315. // Extract the raw linear data.
  83316. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83317. // Generate harmonics if needed.
  83318. if (_this._generateHarmonics) {
  83319. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83320. _this.sphericalPolynomial = sphericalPolynomial;
  83321. }
  83322. var results = [];
  83323. var byteArray = null;
  83324. // Push each faces.
  83325. for (var j = 0; j < 6; j++) {
  83326. // Create uintarray fallback.
  83327. if (!scene.getEngine().getCaps().textureFloat) {
  83328. // 3 channels of 1 bytes per pixel in bytes.
  83329. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83330. byteArray = new Uint8Array(byteBuffer);
  83331. }
  83332. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83333. // If special cases.
  83334. if (_this.gammaSpace || byteArray) {
  83335. for (var i = 0; i < _this._size * _this._size; i++) {
  83336. // Put in gamma space if requested.
  83337. if (_this.gammaSpace) {
  83338. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83339. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83340. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83341. }
  83342. // Convert to int texture for fallback.
  83343. if (byteArray) {
  83344. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83345. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83346. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83347. // May use luminance instead if the result is not accurate.
  83348. var max = Math.max(Math.max(r, g), b);
  83349. if (max > 255) {
  83350. var scale = 255 / max;
  83351. r *= scale;
  83352. g *= scale;
  83353. b *= scale;
  83354. }
  83355. byteArray[(i * 3) + 0] = r;
  83356. byteArray[(i * 3) + 1] = g;
  83357. byteArray[(i * 3) + 2] = b;
  83358. }
  83359. }
  83360. }
  83361. if (byteArray) {
  83362. results.push(byteArray);
  83363. }
  83364. else {
  83365. results.push(dataFace);
  83366. }
  83367. }
  83368. return results;
  83369. };
  83370. var scene = this.getScene();
  83371. if (scene) {
  83372. 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);
  83373. }
  83374. };
  83375. HDRCubeTexture.prototype.clone = function () {
  83376. var scene = this.getScene();
  83377. if (!scene) {
  83378. return this;
  83379. }
  83380. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83381. // Base texture
  83382. newTexture.level = this.level;
  83383. newTexture.wrapU = this.wrapU;
  83384. newTexture.wrapV = this.wrapV;
  83385. newTexture.coordinatesIndex = this.coordinatesIndex;
  83386. newTexture.coordinatesMode = this.coordinatesMode;
  83387. return newTexture;
  83388. };
  83389. // Methods
  83390. HDRCubeTexture.prototype.delayLoad = function () {
  83391. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83392. return;
  83393. }
  83394. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83395. this._texture = this._getFromCache(this.url, this._noMipmap);
  83396. if (!this._texture) {
  83397. this.loadTexture();
  83398. }
  83399. };
  83400. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83401. return this._textureMatrix;
  83402. };
  83403. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83404. this._textureMatrix = value;
  83405. };
  83406. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83407. var texture = null;
  83408. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83409. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83410. texture.name = parsedTexture.name;
  83411. texture.hasAlpha = parsedTexture.hasAlpha;
  83412. texture.level = parsedTexture.level;
  83413. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83414. texture.isBlocking = parsedTexture.isBlocking;
  83415. }
  83416. if (texture) {
  83417. if (parsedTexture.boundingBoxPosition) {
  83418. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83419. }
  83420. if (parsedTexture.boundingBoxSize) {
  83421. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83422. }
  83423. if (parsedTexture.rotationY) {
  83424. texture.rotationY = parsedTexture.rotationY;
  83425. }
  83426. }
  83427. return texture;
  83428. };
  83429. HDRCubeTexture.prototype.serialize = function () {
  83430. if (!this.name) {
  83431. return null;
  83432. }
  83433. var serializationObject = {};
  83434. serializationObject.name = this.name;
  83435. serializationObject.hasAlpha = this.hasAlpha;
  83436. serializationObject.isCube = true;
  83437. serializationObject.level = this.level;
  83438. serializationObject.size = this._size;
  83439. serializationObject.coordinatesMode = this.coordinatesMode;
  83440. serializationObject.useInGammaSpace = this.gammaSpace;
  83441. serializationObject.generateHarmonics = this._generateHarmonics;
  83442. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83443. serializationObject.noMipmap = this._noMipmap;
  83444. serializationObject.isBlocking = this._isBlocking;
  83445. serializationObject.rotationY = this._rotationY;
  83446. return serializationObject;
  83447. };
  83448. HDRCubeTexture._facesMapping = [
  83449. "right",
  83450. "left",
  83451. "up",
  83452. "down",
  83453. "front",
  83454. "back"
  83455. ];
  83456. return HDRCubeTexture;
  83457. }(BABYLON.BaseTexture));
  83458. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83459. })(BABYLON || (BABYLON = {}));
  83460. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83461. var BABYLON;
  83462. (function (BABYLON) {
  83463. /**
  83464. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  83465. */
  83466. var PanoramaToCubeMapTools = /** @class */ (function () {
  83467. function PanoramaToCubeMapTools() {
  83468. }
  83469. /**
  83470. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  83471. *
  83472. * @param float32Array The source data.
  83473. * @param inputWidth The width of the input panorama.
  83474. * @param inputhHeight The height of the input panorama.
  83475. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  83476. * @return The cubemap data
  83477. */
  83478. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  83479. if (!float32Array) {
  83480. throw "ConvertPanoramaToCubemap: input cannot be null";
  83481. }
  83482. if (float32Array.length != inputWidth * inputHeight * 3) {
  83483. throw "ConvertPanoramaToCubemap: input size is wrong";
  83484. }
  83485. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  83486. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  83487. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  83488. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  83489. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  83490. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  83491. return {
  83492. front: textureFront,
  83493. back: textureBack,
  83494. left: textureLeft,
  83495. right: textureRight,
  83496. up: textureUp,
  83497. down: textureDown,
  83498. size: size,
  83499. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  83500. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  83501. gammaSpace: false,
  83502. };
  83503. };
  83504. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  83505. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  83506. var textureArray = new Float32Array(buffer);
  83507. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  83508. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  83509. var dy = 1 / texSize;
  83510. var fy = 0;
  83511. for (var y = 0; y < texSize; y++) {
  83512. var xv1 = faceData[0];
  83513. var xv2 = faceData[2];
  83514. for (var x = 0; x < texSize; x++) {
  83515. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  83516. v.normalize();
  83517. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  83518. // 3 channels per pixels
  83519. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  83520. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  83521. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  83522. xv1 = xv1.add(rotDX1);
  83523. xv2 = xv2.add(rotDX2);
  83524. }
  83525. fy += dy;
  83526. }
  83527. return textureArray;
  83528. };
  83529. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  83530. var theta = Math.atan2(vDir.z, vDir.x);
  83531. var phi = Math.acos(vDir.y);
  83532. while (theta < -Math.PI)
  83533. theta += 2 * Math.PI;
  83534. while (theta > Math.PI)
  83535. theta -= 2 * Math.PI;
  83536. var dx = theta / Math.PI;
  83537. var dy = phi / Math.PI;
  83538. // recenter.
  83539. dx = dx * 0.5 + 0.5;
  83540. var px = Math.round(dx * inputWidth);
  83541. if (px < 0)
  83542. px = 0;
  83543. else if (px >= inputWidth)
  83544. px = inputWidth - 1;
  83545. var py = Math.round(dy * inputHeight);
  83546. if (py < 0)
  83547. py = 0;
  83548. else if (py >= inputHeight)
  83549. py = inputHeight - 1;
  83550. var inputY = (inputHeight - py - 1);
  83551. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  83552. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  83553. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  83554. return {
  83555. r: r,
  83556. g: g,
  83557. b: b
  83558. };
  83559. };
  83560. PanoramaToCubeMapTools.FACE_FRONT = [
  83561. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83562. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83563. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83564. new BABYLON.Vector3(1.0, 1.0, -1.0)
  83565. ];
  83566. PanoramaToCubeMapTools.FACE_BACK = [
  83567. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83568. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83569. new BABYLON.Vector3(1.0, 1.0, 1.0),
  83570. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  83571. ];
  83572. PanoramaToCubeMapTools.FACE_RIGHT = [
  83573. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83574. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83575. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83576. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83577. ];
  83578. PanoramaToCubeMapTools.FACE_LEFT = [
  83579. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83580. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83581. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83582. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  83583. ];
  83584. PanoramaToCubeMapTools.FACE_DOWN = [
  83585. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83586. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83587. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83588. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83589. ];
  83590. PanoramaToCubeMapTools.FACE_UP = [
  83591. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83592. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83593. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83594. new BABYLON.Vector3(1.0, -1.0, -1.0)
  83595. ];
  83596. return PanoramaToCubeMapTools;
  83597. }());
  83598. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  83599. })(BABYLON || (BABYLON = {}));
  83600. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  83601. var BABYLON;
  83602. (function (BABYLON) {
  83603. var IndexedVector2 = /** @class */ (function (_super) {
  83604. __extends(IndexedVector2, _super);
  83605. function IndexedVector2(original, index) {
  83606. var _this = _super.call(this, original.x, original.y) || this;
  83607. _this.index = index;
  83608. return _this;
  83609. }
  83610. return IndexedVector2;
  83611. }(BABYLON.Vector2));
  83612. var PolygonPoints = /** @class */ (function () {
  83613. function PolygonPoints() {
  83614. this.elements = new Array();
  83615. }
  83616. PolygonPoints.prototype.add = function (originalPoints) {
  83617. var _this = this;
  83618. var result = new Array();
  83619. originalPoints.forEach(function (point) {
  83620. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83621. var newPoint = new IndexedVector2(point, _this.elements.length);
  83622. result.push(newPoint);
  83623. _this.elements.push(newPoint);
  83624. }
  83625. });
  83626. return result;
  83627. };
  83628. PolygonPoints.prototype.computeBounds = function () {
  83629. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83630. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83631. this.elements.forEach(function (point) {
  83632. // x
  83633. if (point.x < lmin.x) {
  83634. lmin.x = point.x;
  83635. }
  83636. else if (point.x > lmax.x) {
  83637. lmax.x = point.x;
  83638. }
  83639. // y
  83640. if (point.y < lmin.y) {
  83641. lmin.y = point.y;
  83642. }
  83643. else if (point.y > lmax.y) {
  83644. lmax.y = point.y;
  83645. }
  83646. });
  83647. return {
  83648. min: lmin,
  83649. max: lmax,
  83650. width: lmax.x - lmin.x,
  83651. height: lmax.y - lmin.y
  83652. };
  83653. };
  83654. return PolygonPoints;
  83655. }());
  83656. var Polygon = /** @class */ (function () {
  83657. function Polygon() {
  83658. }
  83659. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83660. return [
  83661. new BABYLON.Vector2(xmin, ymin),
  83662. new BABYLON.Vector2(xmax, ymin),
  83663. new BABYLON.Vector2(xmax, ymax),
  83664. new BABYLON.Vector2(xmin, ymax)
  83665. ];
  83666. };
  83667. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83668. if (cx === void 0) { cx = 0; }
  83669. if (cy === void 0) { cy = 0; }
  83670. if (numberOfSides === void 0) { numberOfSides = 32; }
  83671. var result = new Array();
  83672. var angle = 0;
  83673. var increment = (Math.PI * 2) / numberOfSides;
  83674. for (var i = 0; i < numberOfSides; i++) {
  83675. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83676. angle -= increment;
  83677. }
  83678. return result;
  83679. };
  83680. Polygon.Parse = function (input) {
  83681. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83682. var i, result = [];
  83683. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83684. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83685. }
  83686. return result;
  83687. };
  83688. Polygon.StartingAt = function (x, y) {
  83689. return BABYLON.Path2.StartingAt(x, y);
  83690. };
  83691. return Polygon;
  83692. }());
  83693. BABYLON.Polygon = Polygon;
  83694. var PolygonMeshBuilder = /** @class */ (function () {
  83695. function PolygonMeshBuilder(name, contours, scene) {
  83696. this._points = new PolygonPoints();
  83697. this._outlinepoints = new PolygonPoints();
  83698. this._holes = new Array();
  83699. this._epoints = new Array();
  83700. this._eholes = new Array();
  83701. this._name = name;
  83702. this._scene = scene;
  83703. var points;
  83704. if (contours instanceof BABYLON.Path2) {
  83705. points = contours.getPoints();
  83706. }
  83707. else {
  83708. points = contours;
  83709. }
  83710. this._addToepoint(points);
  83711. this._points.add(points);
  83712. this._outlinepoints.add(points);
  83713. if (typeof earcut === 'undefined') {
  83714. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83715. }
  83716. }
  83717. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83718. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83719. var p = points_1[_i];
  83720. this._epoints.push(p.x, p.y);
  83721. }
  83722. };
  83723. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83724. this._points.add(hole);
  83725. var holepoints = new PolygonPoints();
  83726. holepoints.add(hole);
  83727. this._holes.push(holepoints);
  83728. this._eholes.push(this._epoints.length / 2);
  83729. this._addToepoint(hole);
  83730. return this;
  83731. };
  83732. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83733. var _this = this;
  83734. if (updatable === void 0) { updatable = false; }
  83735. if (depth === void 0) { depth = 0; }
  83736. var result = new BABYLON.Mesh(this._name, this._scene);
  83737. var normals = new Array();
  83738. var positions = new Array();
  83739. var uvs = new Array();
  83740. var bounds = this._points.computeBounds();
  83741. this._points.elements.forEach(function (p) {
  83742. normals.push(0, 1.0, 0);
  83743. positions.push(p.x, 0, p.y);
  83744. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83745. });
  83746. var indices = new Array();
  83747. var res = earcut(this._epoints, this._eholes, 2);
  83748. for (var i = 0; i < res.length; i++) {
  83749. indices.push(res[i]);
  83750. }
  83751. if (depth > 0) {
  83752. var positionscount = (positions.length / 3); //get the current pointcount
  83753. this._points.elements.forEach(function (p) {
  83754. normals.push(0, -1.0, 0);
  83755. positions.push(p.x, -depth, p.y);
  83756. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83757. });
  83758. var totalCount = indices.length;
  83759. for (var i = 0; i < totalCount; i += 3) {
  83760. var i0 = indices[i + 0];
  83761. var i1 = indices[i + 1];
  83762. var i2 = indices[i + 2];
  83763. indices.push(i2 + positionscount);
  83764. indices.push(i1 + positionscount);
  83765. indices.push(i0 + positionscount);
  83766. }
  83767. //Add the sides
  83768. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83769. this._holes.forEach(function (hole) {
  83770. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83771. });
  83772. }
  83773. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83774. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83775. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83776. result.setIndices(indices);
  83777. return result;
  83778. };
  83779. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83780. var StartIndex = positions.length / 3;
  83781. var ulength = 0;
  83782. for (var i = 0; i < points.elements.length; i++) {
  83783. var p = points.elements[i];
  83784. var p1;
  83785. if ((i + 1) > points.elements.length - 1) {
  83786. p1 = points.elements[0];
  83787. }
  83788. else {
  83789. p1 = points.elements[i + 1];
  83790. }
  83791. positions.push(p.x, 0, p.y);
  83792. positions.push(p.x, -depth, p.y);
  83793. positions.push(p1.x, 0, p1.y);
  83794. positions.push(p1.x, -depth, p1.y);
  83795. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83796. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83797. var v3 = v2.subtract(v1);
  83798. var v4 = new BABYLON.Vector3(0, 1, 0);
  83799. var vn = BABYLON.Vector3.Cross(v3, v4);
  83800. vn = vn.normalize();
  83801. uvs.push(ulength / bounds.width, 0);
  83802. uvs.push(ulength / bounds.width, 1);
  83803. ulength += v3.length();
  83804. uvs.push((ulength / bounds.width), 0);
  83805. uvs.push((ulength / bounds.width), 1);
  83806. if (!flip) {
  83807. normals.push(-vn.x, -vn.y, -vn.z);
  83808. normals.push(-vn.x, -vn.y, -vn.z);
  83809. normals.push(-vn.x, -vn.y, -vn.z);
  83810. normals.push(-vn.x, -vn.y, -vn.z);
  83811. indices.push(StartIndex);
  83812. indices.push(StartIndex + 1);
  83813. indices.push(StartIndex + 2);
  83814. indices.push(StartIndex + 1);
  83815. indices.push(StartIndex + 3);
  83816. indices.push(StartIndex + 2);
  83817. }
  83818. else {
  83819. normals.push(vn.x, vn.y, vn.z);
  83820. normals.push(vn.x, vn.y, vn.z);
  83821. normals.push(vn.x, vn.y, vn.z);
  83822. normals.push(vn.x, vn.y, vn.z);
  83823. indices.push(StartIndex);
  83824. indices.push(StartIndex + 2);
  83825. indices.push(StartIndex + 1);
  83826. indices.push(StartIndex + 1);
  83827. indices.push(StartIndex + 2);
  83828. indices.push(StartIndex + 3);
  83829. }
  83830. StartIndex += 4;
  83831. }
  83832. ;
  83833. };
  83834. return PolygonMeshBuilder;
  83835. }());
  83836. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83837. })(BABYLON || (BABYLON = {}));
  83838. //# sourceMappingURL=babylon.polygonMesh.js.map
  83839. var BABYLON;
  83840. (function (BABYLON) {
  83841. // Unique ID when we import meshes from Babylon to CSG
  83842. var currentCSGMeshId = 0;
  83843. // # class Vertex
  83844. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83845. // one to provide additional features like texture coordinates and vertex
  83846. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83847. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83848. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83849. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83850. // is not used anywhere else.
  83851. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83852. var Vertex = /** @class */ (function () {
  83853. function Vertex(pos, normal, uv) {
  83854. this.pos = pos;
  83855. this.normal = normal;
  83856. this.uv = uv;
  83857. }
  83858. Vertex.prototype.clone = function () {
  83859. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83860. };
  83861. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83862. // orientation of a polygon is flipped.
  83863. Vertex.prototype.flip = function () {
  83864. this.normal = this.normal.scale(-1);
  83865. };
  83866. // Create a new vertex between this vertex and `other` by linearly
  83867. // interpolating all properties using a parameter of `t`. Subclasses should
  83868. // override this to interpolate additional properties.
  83869. Vertex.prototype.interpolate = function (other, t) {
  83870. 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));
  83871. };
  83872. return Vertex;
  83873. }());
  83874. // # class Plane
  83875. // Represents a plane in 3D space.
  83876. var Plane = /** @class */ (function () {
  83877. function Plane(normal, w) {
  83878. this.normal = normal;
  83879. this.w = w;
  83880. }
  83881. Plane.FromPoints = function (a, b, c) {
  83882. var v0 = c.subtract(a);
  83883. var v1 = b.subtract(a);
  83884. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83885. return null;
  83886. }
  83887. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83888. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83889. };
  83890. Plane.prototype.clone = function () {
  83891. return new Plane(this.normal.clone(), this.w);
  83892. };
  83893. Plane.prototype.flip = function () {
  83894. this.normal.scaleInPlace(-1);
  83895. this.w = -this.w;
  83896. };
  83897. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83898. // fragments in the appropriate lists. Coplanar polygons go into either
  83899. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83900. // respect to this plane. Polygons in front or in back of this plane go into
  83901. // either `front` or `back`.
  83902. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83903. var COPLANAR = 0;
  83904. var FRONT = 1;
  83905. var BACK = 2;
  83906. var SPANNING = 3;
  83907. // Classify each point as well as the entire polygon into one of the above
  83908. // four classes.
  83909. var polygonType = 0;
  83910. var types = [];
  83911. var i;
  83912. var t;
  83913. for (i = 0; i < polygon.vertices.length; i++) {
  83914. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83915. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83916. polygonType |= type;
  83917. types.push(type);
  83918. }
  83919. // Put the polygon in the correct list, splitting it when necessary.
  83920. switch (polygonType) {
  83921. case COPLANAR:
  83922. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83923. break;
  83924. case FRONT:
  83925. front.push(polygon);
  83926. break;
  83927. case BACK:
  83928. back.push(polygon);
  83929. break;
  83930. case SPANNING:
  83931. var f = [], b = [];
  83932. for (i = 0; i < polygon.vertices.length; i++) {
  83933. var j = (i + 1) % polygon.vertices.length;
  83934. var ti = types[i], tj = types[j];
  83935. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83936. if (ti !== BACK)
  83937. f.push(vi);
  83938. if (ti !== FRONT)
  83939. b.push(ti !== BACK ? vi.clone() : vi);
  83940. if ((ti | tj) === SPANNING) {
  83941. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83942. var v = vi.interpolate(vj, t);
  83943. f.push(v);
  83944. b.push(v.clone());
  83945. }
  83946. }
  83947. var poly;
  83948. if (f.length >= 3) {
  83949. poly = new Polygon(f, polygon.shared);
  83950. if (poly.plane)
  83951. front.push(poly);
  83952. }
  83953. if (b.length >= 3) {
  83954. poly = new Polygon(b, polygon.shared);
  83955. if (poly.plane)
  83956. back.push(poly);
  83957. }
  83958. break;
  83959. }
  83960. };
  83961. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83962. // point is on the plane.
  83963. Plane.EPSILON = 1e-5;
  83964. return Plane;
  83965. }());
  83966. // # class Polygon
  83967. // Represents a convex polygon. The vertices used to initialize a polygon must
  83968. // be coplanar and form a convex loop.
  83969. //
  83970. // Each convex polygon has a `shared` property, which is shared between all
  83971. // polygons that are clones of each other or were split from the same polygon.
  83972. // This can be used to define per-polygon properties (such as surface color).
  83973. var Polygon = /** @class */ (function () {
  83974. function Polygon(vertices, shared) {
  83975. this.vertices = vertices;
  83976. this.shared = shared;
  83977. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83978. }
  83979. Polygon.prototype.clone = function () {
  83980. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83981. return new Polygon(vertices, this.shared);
  83982. };
  83983. Polygon.prototype.flip = function () {
  83984. this.vertices.reverse().map(function (v) { v.flip(); });
  83985. this.plane.flip();
  83986. };
  83987. return Polygon;
  83988. }());
  83989. // # class Node
  83990. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83991. // by picking a polygon to split along. That polygon (and all other coplanar
  83992. // polygons) are added directly to that node and the other polygons are added to
  83993. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83994. // no distinction between internal and leaf nodes.
  83995. var Node = /** @class */ (function () {
  83996. function Node(polygons) {
  83997. this.plane = null;
  83998. this.front = null;
  83999. this.back = null;
  84000. this.polygons = new Array();
  84001. if (polygons) {
  84002. this.build(polygons);
  84003. }
  84004. }
  84005. Node.prototype.clone = function () {
  84006. var node = new Node();
  84007. node.plane = this.plane && this.plane.clone();
  84008. node.front = this.front && this.front.clone();
  84009. node.back = this.back && this.back.clone();
  84010. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  84011. return node;
  84012. };
  84013. // Convert solid space to empty space and empty space to solid space.
  84014. Node.prototype.invert = function () {
  84015. for (var i = 0; i < this.polygons.length; i++) {
  84016. this.polygons[i].flip();
  84017. }
  84018. if (this.plane) {
  84019. this.plane.flip();
  84020. }
  84021. if (this.front) {
  84022. this.front.invert();
  84023. }
  84024. if (this.back) {
  84025. this.back.invert();
  84026. }
  84027. var temp = this.front;
  84028. this.front = this.back;
  84029. this.back = temp;
  84030. };
  84031. // Recursively remove all polygons in `polygons` that are inside this BSP
  84032. // tree.
  84033. Node.prototype.clipPolygons = function (polygons) {
  84034. if (!this.plane)
  84035. return polygons.slice();
  84036. var front = new Array(), back = new Array();
  84037. for (var i = 0; i < polygons.length; i++) {
  84038. this.plane.splitPolygon(polygons[i], front, back, front, back);
  84039. }
  84040. if (this.front) {
  84041. front = this.front.clipPolygons(front);
  84042. }
  84043. if (this.back) {
  84044. back = this.back.clipPolygons(back);
  84045. }
  84046. else {
  84047. back = [];
  84048. }
  84049. return front.concat(back);
  84050. };
  84051. // Remove all polygons in this BSP tree that are inside the other BSP tree
  84052. // `bsp`.
  84053. Node.prototype.clipTo = function (bsp) {
  84054. this.polygons = bsp.clipPolygons(this.polygons);
  84055. if (this.front)
  84056. this.front.clipTo(bsp);
  84057. if (this.back)
  84058. this.back.clipTo(bsp);
  84059. };
  84060. // Return a list of all polygons in this BSP tree.
  84061. Node.prototype.allPolygons = function () {
  84062. var polygons = this.polygons.slice();
  84063. if (this.front)
  84064. polygons = polygons.concat(this.front.allPolygons());
  84065. if (this.back)
  84066. polygons = polygons.concat(this.back.allPolygons());
  84067. return polygons;
  84068. };
  84069. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  84070. // new polygons are filtered down to the bottom of the tree and become new
  84071. // nodes there. Each set of polygons is partitioned using the first polygon
  84072. // (no heuristic is used to pick a good split).
  84073. Node.prototype.build = function (polygons) {
  84074. if (!polygons.length)
  84075. return;
  84076. if (!this.plane)
  84077. this.plane = polygons[0].plane.clone();
  84078. var front = new Array(), back = new Array();
  84079. for (var i = 0; i < polygons.length; i++) {
  84080. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  84081. }
  84082. if (front.length) {
  84083. if (!this.front)
  84084. this.front = new Node();
  84085. this.front.build(front);
  84086. }
  84087. if (back.length) {
  84088. if (!this.back)
  84089. this.back = new Node();
  84090. this.back.build(back);
  84091. }
  84092. };
  84093. return Node;
  84094. }());
  84095. var CSG = /** @class */ (function () {
  84096. function CSG() {
  84097. this.polygons = new Array();
  84098. }
  84099. // Convert BABYLON.Mesh to BABYLON.CSG
  84100. CSG.FromMesh = function (mesh) {
  84101. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  84102. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  84103. if (mesh instanceof BABYLON.Mesh) {
  84104. mesh.computeWorldMatrix(true);
  84105. matrix = mesh.getWorldMatrix();
  84106. meshPosition = mesh.position.clone();
  84107. meshRotation = mesh.rotation.clone();
  84108. if (mesh.rotationQuaternion) {
  84109. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  84110. }
  84111. meshScaling = mesh.scaling.clone();
  84112. }
  84113. else {
  84114. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  84115. }
  84116. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84117. var subMeshes = mesh.subMeshes;
  84118. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  84119. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  84120. vertices = [];
  84121. for (var j = 0; j < 3; j++) {
  84122. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  84123. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  84124. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  84125. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  84126. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  84127. vertex = new Vertex(position, normal, uv);
  84128. vertices.push(vertex);
  84129. }
  84130. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  84131. // To handle the case of degenerated triangle
  84132. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  84133. if (polygon.plane)
  84134. polygons.push(polygon);
  84135. }
  84136. }
  84137. var csg = CSG.FromPolygons(polygons);
  84138. csg.matrix = matrix;
  84139. csg.position = meshPosition;
  84140. csg.rotation = meshRotation;
  84141. csg.scaling = meshScaling;
  84142. csg.rotationQuaternion = meshRotationQuaternion;
  84143. currentCSGMeshId++;
  84144. return csg;
  84145. };
  84146. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  84147. CSG.FromPolygons = function (polygons) {
  84148. var csg = new CSG();
  84149. csg.polygons = polygons;
  84150. return csg;
  84151. };
  84152. CSG.prototype.clone = function () {
  84153. var csg = new CSG();
  84154. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  84155. csg.copyTransformAttributes(this);
  84156. return csg;
  84157. };
  84158. CSG.prototype.union = function (csg) {
  84159. var a = new Node(this.clone().polygons);
  84160. var b = new Node(csg.clone().polygons);
  84161. a.clipTo(b);
  84162. b.clipTo(a);
  84163. b.invert();
  84164. b.clipTo(a);
  84165. b.invert();
  84166. a.build(b.allPolygons());
  84167. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84168. };
  84169. CSG.prototype.unionInPlace = function (csg) {
  84170. var a = new Node(this.polygons);
  84171. var b = new Node(csg.polygons);
  84172. a.clipTo(b);
  84173. b.clipTo(a);
  84174. b.invert();
  84175. b.clipTo(a);
  84176. b.invert();
  84177. a.build(b.allPolygons());
  84178. this.polygons = a.allPolygons();
  84179. };
  84180. CSG.prototype.subtract = function (csg) {
  84181. var a = new Node(this.clone().polygons);
  84182. var b = new Node(csg.clone().polygons);
  84183. a.invert();
  84184. a.clipTo(b);
  84185. b.clipTo(a);
  84186. b.invert();
  84187. b.clipTo(a);
  84188. b.invert();
  84189. a.build(b.allPolygons());
  84190. a.invert();
  84191. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84192. };
  84193. CSG.prototype.subtractInPlace = function (csg) {
  84194. var a = new Node(this.polygons);
  84195. var b = new Node(csg.polygons);
  84196. a.invert();
  84197. a.clipTo(b);
  84198. b.clipTo(a);
  84199. b.invert();
  84200. b.clipTo(a);
  84201. b.invert();
  84202. a.build(b.allPolygons());
  84203. a.invert();
  84204. this.polygons = a.allPolygons();
  84205. };
  84206. CSG.prototype.intersect = function (csg) {
  84207. var a = new Node(this.clone().polygons);
  84208. var b = new Node(csg.clone().polygons);
  84209. a.invert();
  84210. b.clipTo(a);
  84211. b.invert();
  84212. a.clipTo(b);
  84213. b.clipTo(a);
  84214. a.build(b.allPolygons());
  84215. a.invert();
  84216. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84217. };
  84218. CSG.prototype.intersectInPlace = function (csg) {
  84219. var a = new Node(this.polygons);
  84220. var b = new Node(csg.polygons);
  84221. a.invert();
  84222. b.clipTo(a);
  84223. b.invert();
  84224. a.clipTo(b);
  84225. b.clipTo(a);
  84226. a.build(b.allPolygons());
  84227. a.invert();
  84228. this.polygons = a.allPolygons();
  84229. };
  84230. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  84231. // not modified.
  84232. CSG.prototype.inverse = function () {
  84233. var csg = this.clone();
  84234. csg.inverseInPlace();
  84235. return csg;
  84236. };
  84237. CSG.prototype.inverseInPlace = function () {
  84238. this.polygons.map(function (p) { p.flip(); });
  84239. };
  84240. // This is used to keep meshes transformations so they can be restored
  84241. // when we build back a Babylon Mesh
  84242. // NB : All CSG operations are performed in world coordinates
  84243. CSG.prototype.copyTransformAttributes = function (csg) {
  84244. this.matrix = csg.matrix;
  84245. this.position = csg.position;
  84246. this.rotation = csg.rotation;
  84247. this.scaling = csg.scaling;
  84248. this.rotationQuaternion = csg.rotationQuaternion;
  84249. return this;
  84250. };
  84251. // Build Raw mesh from CSG
  84252. // Coordinates here are in world space
  84253. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  84254. var matrix = this.matrix.clone();
  84255. matrix.invert();
  84256. 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;
  84257. if (keepSubMeshes) {
  84258. // Sort Polygons, since subMeshes are indices range
  84259. polygons.sort(function (a, b) {
  84260. if (a.shared.meshId === b.shared.meshId) {
  84261. return a.shared.subMeshId - b.shared.subMeshId;
  84262. }
  84263. else {
  84264. return a.shared.meshId - b.shared.meshId;
  84265. }
  84266. });
  84267. }
  84268. for (var i = 0, il = polygons.length; i < il; i++) {
  84269. polygon = polygons[i];
  84270. // Building SubMeshes
  84271. if (!subMesh_dict[polygon.shared.meshId]) {
  84272. subMesh_dict[polygon.shared.meshId] = {};
  84273. }
  84274. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  84275. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  84276. indexStart: +Infinity,
  84277. indexEnd: -Infinity,
  84278. materialIndex: polygon.shared.materialIndex
  84279. };
  84280. }
  84281. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84282. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84283. polygonIndices[0] = 0;
  84284. polygonIndices[1] = j - 1;
  84285. polygonIndices[2] = j;
  84286. for (var k = 0; k < 3; k++) {
  84287. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84288. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84289. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84290. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84291. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84292. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84293. // Check if 2 points can be merged
  84294. if (!(typeof vertex_idx !== 'undefined' &&
  84295. normals[vertex_idx * 3] === localNormal.x &&
  84296. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84297. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84298. uvs[vertex_idx * 2] === uv.x &&
  84299. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84300. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84301. uvs.push(uv.x, uv.y);
  84302. normals.push(normal.x, normal.y, normal.z);
  84303. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84304. }
  84305. indices.push(vertex_idx);
  84306. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84307. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84308. currentIndex++;
  84309. }
  84310. }
  84311. }
  84312. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84313. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84314. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84315. mesh.setIndices(indices, null);
  84316. if (keepSubMeshes) {
  84317. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84318. var materialIndexOffset = 0, materialMaxIndex;
  84319. mesh.subMeshes = new Array();
  84320. for (var m in subMesh_dict) {
  84321. materialMaxIndex = -1;
  84322. for (var sm in subMesh_dict[m]) {
  84323. subMesh_obj = subMesh_dict[m][sm];
  84324. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84325. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84326. }
  84327. materialIndexOffset += ++materialMaxIndex;
  84328. }
  84329. }
  84330. return mesh;
  84331. };
  84332. // Build Mesh from CSG taking material and transforms into account
  84333. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84334. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84335. mesh.material = material;
  84336. mesh.position.copyFrom(this.position);
  84337. mesh.rotation.copyFrom(this.rotation);
  84338. if (this.rotationQuaternion) {
  84339. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84340. }
  84341. mesh.scaling.copyFrom(this.scaling);
  84342. mesh.computeWorldMatrix(true);
  84343. return mesh;
  84344. };
  84345. return CSG;
  84346. }());
  84347. BABYLON.CSG = CSG;
  84348. })(BABYLON || (BABYLON = {}));
  84349. //# sourceMappingURL=babylon.csg.js.map
  84350. var BABYLON;
  84351. (function (BABYLON) {
  84352. var LensFlare = /** @class */ (function () {
  84353. function LensFlare(size, position, color, imgUrl, system) {
  84354. this.size = size;
  84355. this.position = position;
  84356. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84357. this.color = color || new BABYLON.Color3(1, 1, 1);
  84358. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84359. this._system = system;
  84360. system.lensFlares.push(this);
  84361. }
  84362. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84363. return new LensFlare(size, position, color, imgUrl, system);
  84364. };
  84365. LensFlare.prototype.dispose = function () {
  84366. if (this.texture) {
  84367. this.texture.dispose();
  84368. }
  84369. // Remove from scene
  84370. var index = this._system.lensFlares.indexOf(this);
  84371. this._system.lensFlares.splice(index, 1);
  84372. };
  84373. ;
  84374. return LensFlare;
  84375. }());
  84376. BABYLON.LensFlare = LensFlare;
  84377. })(BABYLON || (BABYLON = {}));
  84378. //# sourceMappingURL=babylon.lensFlare.js.map
  84379. var BABYLON;
  84380. (function (BABYLON) {
  84381. // Adds the parser to the scene parsers.
  84382. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84383. // Lens flares
  84384. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84385. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84386. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84387. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84388. container.lensFlareSystems.push(lf);
  84389. }
  84390. }
  84391. });
  84392. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84393. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84394. if (this.lensFlareSystems[index].name === name) {
  84395. return this.lensFlareSystems[index];
  84396. }
  84397. }
  84398. return null;
  84399. };
  84400. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84401. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84402. if (this.lensFlareSystems[index].id === id) {
  84403. return this.lensFlareSystems[index];
  84404. }
  84405. }
  84406. return null;
  84407. };
  84408. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84409. var index = this.lensFlareSystems.indexOf(toRemove);
  84410. if (index !== -1) {
  84411. this.lensFlareSystems.splice(index, 1);
  84412. }
  84413. return index;
  84414. };
  84415. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84416. this.lensFlareSystems.push(newLensFlareSystem);
  84417. };
  84418. /**
  84419. * Defines the lens flare scene component responsible to manage any lens flares
  84420. * in a given scene.
  84421. */
  84422. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84423. /**
  84424. * Creates a new instance of the component for the given scene
  84425. * @param scene Defines the scene to register the component in
  84426. */
  84427. function LensFlareSystemSceneComponent(scene) {
  84428. /**
  84429. * The component name helpfull to identify the component in the list of scene components.
  84430. */
  84431. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84432. this.scene = scene;
  84433. scene.lensFlareSystems = new Array();
  84434. }
  84435. /**
  84436. * Registers the component in a given scene
  84437. */
  84438. LensFlareSystemSceneComponent.prototype.register = function () {
  84439. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84440. };
  84441. /**
  84442. * Rebuilds the elements related to this component in case of
  84443. * context lost for instance.
  84444. */
  84445. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84446. // Nothing to do for lens flare
  84447. };
  84448. /**
  84449. * Adds all the element from the container to the scene
  84450. * @param container the container holding the elements
  84451. */
  84452. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84453. var _this = this;
  84454. if (!container.lensFlareSystems) {
  84455. return;
  84456. }
  84457. container.lensFlareSystems.forEach(function (o) {
  84458. _this.scene.addLensFlareSystem(o);
  84459. });
  84460. };
  84461. /**
  84462. * Removes all the elements in the container from the scene
  84463. * @param container contains the elements to remove
  84464. */
  84465. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84466. var _this = this;
  84467. if (!container.lensFlareSystems) {
  84468. return;
  84469. }
  84470. container.lensFlareSystems.forEach(function (o) {
  84471. _this.scene.removeLensFlareSystem(o);
  84472. });
  84473. };
  84474. /**
  84475. * Serializes the component data to the specified json object
  84476. * @param serializationObject The object to serialize to
  84477. */
  84478. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84479. // Lens flares
  84480. serializationObject.lensFlareSystems = [];
  84481. var lensFlareSystems = this.scene.lensFlareSystems;
  84482. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  84483. var lensFlareSystem = lensFlareSystems_1[_i];
  84484. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84485. }
  84486. };
  84487. /**
  84488. * Disposes the component and the associated ressources.
  84489. */
  84490. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84491. var lensFlareSystems = this.scene.lensFlareSystems;
  84492. while (lensFlareSystems.length) {
  84493. lensFlareSystems[0].dispose();
  84494. }
  84495. };
  84496. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84497. // Lens flares
  84498. if (this.scene.lensFlaresEnabled) {
  84499. var lensFlareSystems = this.scene.lensFlareSystems;
  84500. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84501. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  84502. var lensFlareSystem = lensFlareSystems_2[_i];
  84503. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84504. lensFlareSystem.render();
  84505. }
  84506. }
  84507. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84508. }
  84509. };
  84510. return LensFlareSystemSceneComponent;
  84511. }());
  84512. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84513. })(BABYLON || (BABYLON = {}));
  84514. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84515. var BABYLON;
  84516. (function (BABYLON) {
  84517. var LensFlareSystem = /** @class */ (function () {
  84518. function LensFlareSystem(name, emitter, scene) {
  84519. this.name = name;
  84520. this.lensFlares = new Array();
  84521. this.borderLimit = 300;
  84522. this.viewportBorder = 0;
  84523. this.layerMask = 0x0FFFFFFF;
  84524. this._vertexBuffers = {};
  84525. this._isEnabled = true;
  84526. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84527. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84528. if (!component) {
  84529. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84530. scene._addComponent(component);
  84531. }
  84532. this._emitter = emitter;
  84533. this.id = name;
  84534. scene.lensFlareSystems.push(this);
  84535. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84536. var engine = scene.getEngine();
  84537. // VBO
  84538. var vertices = [];
  84539. vertices.push(1, 1);
  84540. vertices.push(-1, 1);
  84541. vertices.push(-1, -1);
  84542. vertices.push(1, -1);
  84543. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84544. // Indices
  84545. var indices = [];
  84546. indices.push(0);
  84547. indices.push(1);
  84548. indices.push(2);
  84549. indices.push(0);
  84550. indices.push(2);
  84551. indices.push(3);
  84552. this._indexBuffer = engine.createIndexBuffer(indices);
  84553. // Effects
  84554. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84555. }
  84556. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84557. get: function () {
  84558. return this._isEnabled;
  84559. },
  84560. set: function (value) {
  84561. this._isEnabled = value;
  84562. },
  84563. enumerable: true,
  84564. configurable: true
  84565. });
  84566. LensFlareSystem.prototype.getScene = function () {
  84567. return this._scene;
  84568. };
  84569. LensFlareSystem.prototype.getEmitter = function () {
  84570. return this._emitter;
  84571. };
  84572. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84573. this._emitter = newEmitter;
  84574. };
  84575. LensFlareSystem.prototype.getEmitterPosition = function () {
  84576. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84577. };
  84578. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84579. var position = this.getEmitterPosition();
  84580. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84581. this._positionX = position.x;
  84582. this._positionY = position.y;
  84583. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84584. if (this.viewportBorder > 0) {
  84585. globalViewport.x -= this.viewportBorder;
  84586. globalViewport.y -= this.viewportBorder;
  84587. globalViewport.width += this.viewportBorder * 2;
  84588. globalViewport.height += this.viewportBorder * 2;
  84589. position.x += this.viewportBorder;
  84590. position.y += this.viewportBorder;
  84591. this._positionX += this.viewportBorder;
  84592. this._positionY += this.viewportBorder;
  84593. }
  84594. if (position.z > 0) {
  84595. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84596. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84597. return true;
  84598. }
  84599. return true;
  84600. }
  84601. return false;
  84602. };
  84603. LensFlareSystem.prototype._isVisible = function () {
  84604. if (!this._isEnabled || !this._scene.activeCamera) {
  84605. return false;
  84606. }
  84607. var emitterPosition = this.getEmitterPosition();
  84608. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84609. var distance = direction.length();
  84610. direction.normalize();
  84611. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84612. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84613. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84614. };
  84615. LensFlareSystem.prototype.render = function () {
  84616. if (!this._effect.isReady() || !this._scene.activeCamera)
  84617. return false;
  84618. var engine = this._scene.getEngine();
  84619. var viewport = this._scene.activeCamera.viewport;
  84620. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84621. // Position
  84622. if (!this.computeEffectivePosition(globalViewport)) {
  84623. return false;
  84624. }
  84625. // Visibility
  84626. if (!this._isVisible()) {
  84627. return false;
  84628. }
  84629. // Intensity
  84630. var awayX;
  84631. var awayY;
  84632. if (this._positionX < this.borderLimit + globalViewport.x) {
  84633. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84634. }
  84635. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84636. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84637. }
  84638. else {
  84639. awayX = 0;
  84640. }
  84641. if (this._positionY < this.borderLimit + globalViewport.y) {
  84642. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84643. }
  84644. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84645. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84646. }
  84647. else {
  84648. awayY = 0;
  84649. }
  84650. var away = (awayX > awayY) ? awayX : awayY;
  84651. away -= this.viewportBorder;
  84652. if (away > this.borderLimit) {
  84653. away = this.borderLimit;
  84654. }
  84655. var intensity = 1.0 - (away / this.borderLimit);
  84656. if (intensity < 0) {
  84657. return false;
  84658. }
  84659. if (intensity > 1.0) {
  84660. intensity = 1.0;
  84661. }
  84662. if (this.viewportBorder > 0) {
  84663. globalViewport.x += this.viewportBorder;
  84664. globalViewport.y += this.viewportBorder;
  84665. globalViewport.width -= this.viewportBorder * 2;
  84666. globalViewport.height -= this.viewportBorder * 2;
  84667. this._positionX -= this.viewportBorder;
  84668. this._positionY -= this.viewportBorder;
  84669. }
  84670. // Position
  84671. var centerX = globalViewport.x + globalViewport.width / 2;
  84672. var centerY = globalViewport.y + globalViewport.height / 2;
  84673. var distX = centerX - this._positionX;
  84674. var distY = centerY - this._positionY;
  84675. // Effects
  84676. engine.enableEffect(this._effect);
  84677. engine.setState(false);
  84678. engine.setDepthBuffer(false);
  84679. // VBOs
  84680. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84681. // Flares
  84682. for (var index = 0; index < this.lensFlares.length; index++) {
  84683. var flare = this.lensFlares[index];
  84684. engine.setAlphaMode(flare.alphaMode);
  84685. var x = centerX - (distX * flare.position);
  84686. var y = centerY - (distY * flare.position);
  84687. var cw = flare.size;
  84688. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84689. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84690. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84691. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84692. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84693. // Texture
  84694. this._effect.setTexture("textureSampler", flare.texture);
  84695. // Color
  84696. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84697. // Draw order
  84698. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84699. }
  84700. engine.setDepthBuffer(true);
  84701. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84702. return true;
  84703. };
  84704. LensFlareSystem.prototype.dispose = function () {
  84705. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84706. if (vertexBuffer) {
  84707. vertexBuffer.dispose();
  84708. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84709. }
  84710. if (this._indexBuffer) {
  84711. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84712. this._indexBuffer = null;
  84713. }
  84714. while (this.lensFlares.length) {
  84715. this.lensFlares[0].dispose();
  84716. }
  84717. // Remove from scene
  84718. var index = this._scene.lensFlareSystems.indexOf(this);
  84719. this._scene.lensFlareSystems.splice(index, 1);
  84720. };
  84721. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84722. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84723. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84724. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84725. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84726. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84727. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84728. var parsedFlare = parsedLensFlareSystem.flares[index];
  84729. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84730. }
  84731. return lensFlareSystem;
  84732. };
  84733. LensFlareSystem.prototype.serialize = function () {
  84734. var serializationObject = {};
  84735. serializationObject.id = this.id;
  84736. serializationObject.name = this.name;
  84737. serializationObject.emitterId = this.getEmitter().id;
  84738. serializationObject.borderLimit = this.borderLimit;
  84739. serializationObject.flares = [];
  84740. for (var index = 0; index < this.lensFlares.length; index++) {
  84741. var flare = this.lensFlares[index];
  84742. serializationObject.flares.push({
  84743. size: flare.size,
  84744. position: flare.position,
  84745. color: flare.color.asArray(),
  84746. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84747. });
  84748. }
  84749. return serializationObject;
  84750. };
  84751. return LensFlareSystem;
  84752. }());
  84753. BABYLON.LensFlareSystem = LensFlareSystem;
  84754. })(BABYLON || (BABYLON = {}));
  84755. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84756. var BABYLON;
  84757. (function (BABYLON) {
  84758. /**
  84759. * This is a holder class for the physics joint created by the physics plugin.
  84760. * It holds a set of functions to control the underlying joint.
  84761. */
  84762. var PhysicsJoint = /** @class */ (function () {
  84763. function PhysicsJoint(type, jointData) {
  84764. this.type = type;
  84765. this.jointData = jointData;
  84766. jointData.nativeParams = jointData.nativeParams || {};
  84767. }
  84768. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84769. get: function () {
  84770. return this._physicsJoint;
  84771. },
  84772. set: function (newJoint) {
  84773. if (this._physicsJoint) {
  84774. //remove from the wolrd
  84775. }
  84776. this._physicsJoint = newJoint;
  84777. },
  84778. enumerable: true,
  84779. configurable: true
  84780. });
  84781. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84782. set: function (physicsPlugin) {
  84783. this._physicsPlugin = physicsPlugin;
  84784. },
  84785. enumerable: true,
  84786. configurable: true
  84787. });
  84788. /**
  84789. * Execute a function that is physics-plugin specific.
  84790. * @param {Function} func the function that will be executed.
  84791. * It accepts two parameters: the physics world and the physics joint.
  84792. */
  84793. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84794. func(this._physicsPlugin.world, this._physicsJoint);
  84795. };
  84796. //TODO check if the native joints are the same
  84797. //Joint Types
  84798. PhysicsJoint.DistanceJoint = 0;
  84799. PhysicsJoint.HingeJoint = 1;
  84800. PhysicsJoint.BallAndSocketJoint = 2;
  84801. PhysicsJoint.WheelJoint = 3;
  84802. PhysicsJoint.SliderJoint = 4;
  84803. //OIMO
  84804. PhysicsJoint.PrismaticJoint = 5;
  84805. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84806. PhysicsJoint.UniversalJoint = 6;
  84807. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84808. //Cannon
  84809. //Similar to a Ball-Joint. Different in params
  84810. PhysicsJoint.PointToPointJoint = 8;
  84811. //Cannon only at the moment
  84812. PhysicsJoint.SpringJoint = 9;
  84813. PhysicsJoint.LockJoint = 10;
  84814. return PhysicsJoint;
  84815. }());
  84816. BABYLON.PhysicsJoint = PhysicsJoint;
  84817. /**
  84818. * A class representing a physics distance joint.
  84819. */
  84820. var DistanceJoint = /** @class */ (function (_super) {
  84821. __extends(DistanceJoint, _super);
  84822. function DistanceJoint(jointData) {
  84823. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84824. }
  84825. /**
  84826. * Update the predefined distance.
  84827. */
  84828. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84829. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84830. };
  84831. return DistanceJoint;
  84832. }(PhysicsJoint));
  84833. BABYLON.DistanceJoint = DistanceJoint;
  84834. var MotorEnabledJoint = /** @class */ (function (_super) {
  84835. __extends(MotorEnabledJoint, _super);
  84836. function MotorEnabledJoint(type, jointData) {
  84837. return _super.call(this, type, jointData) || this;
  84838. }
  84839. /**
  84840. * Set the motor values.
  84841. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84842. * @param {number} force the force to apply
  84843. * @param {number} maxForce max force for this motor.
  84844. */
  84845. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84846. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84847. };
  84848. /**
  84849. * Set the motor's limits.
  84850. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84851. */
  84852. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84853. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84854. };
  84855. return MotorEnabledJoint;
  84856. }(PhysicsJoint));
  84857. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84858. /**
  84859. * This class represents a single hinge physics joint
  84860. */
  84861. var HingeJoint = /** @class */ (function (_super) {
  84862. __extends(HingeJoint, _super);
  84863. function HingeJoint(jointData) {
  84864. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84865. }
  84866. /**
  84867. * Set the motor values.
  84868. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84869. * @param {number} force the force to apply
  84870. * @param {number} maxForce max force for this motor.
  84871. */
  84872. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84873. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84874. };
  84875. /**
  84876. * Set the motor's limits.
  84877. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84878. */
  84879. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84880. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84881. };
  84882. return HingeJoint;
  84883. }(MotorEnabledJoint));
  84884. BABYLON.HingeJoint = HingeJoint;
  84885. /**
  84886. * This class represents a dual hinge physics joint (same as wheel joint)
  84887. */
  84888. var Hinge2Joint = /** @class */ (function (_super) {
  84889. __extends(Hinge2Joint, _super);
  84890. function Hinge2Joint(jointData) {
  84891. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84892. }
  84893. /**
  84894. * Set the motor values.
  84895. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84896. * @param {number} force the force to apply
  84897. * @param {number} maxForce max force for this motor.
  84898. * @param {motorIndex} the motor's index, 0 or 1.
  84899. */
  84900. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84901. if (motorIndex === void 0) { motorIndex = 0; }
  84902. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84903. };
  84904. /**
  84905. * Set the motor limits.
  84906. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84907. * @param {number} upperLimit the upper limit
  84908. * @param {number} lowerLimit lower limit
  84909. * @param {motorIndex} the motor's index, 0 or 1.
  84910. */
  84911. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84912. if (motorIndex === void 0) { motorIndex = 0; }
  84913. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84914. };
  84915. return Hinge2Joint;
  84916. }(MotorEnabledJoint));
  84917. BABYLON.Hinge2Joint = Hinge2Joint;
  84918. })(BABYLON || (BABYLON = {}));
  84919. //# sourceMappingURL=babylon.physicsJoint.js.map
  84920. var BABYLON;
  84921. (function (BABYLON) {
  84922. var PhysicsImpostor = /** @class */ (function () {
  84923. function PhysicsImpostor(object, type, _options, _scene) {
  84924. if (_options === void 0) { _options = { mass: 0 }; }
  84925. var _this = this;
  84926. this.object = object;
  84927. this.type = type;
  84928. this._options = _options;
  84929. this._scene = _scene;
  84930. this._bodyUpdateRequired = false;
  84931. this._onBeforePhysicsStepCallbacks = new Array();
  84932. this._onAfterPhysicsStepCallbacks = new Array();
  84933. this._onPhysicsCollideCallbacks = [];
  84934. this._deltaPosition = BABYLON.Vector3.Zero();
  84935. this._isDisposed = false;
  84936. //temp variables for parent rotation calculations
  84937. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84938. this._tmpQuat = new BABYLON.Quaternion();
  84939. this._tmpQuat2 = new BABYLON.Quaternion();
  84940. /**
  84941. * this function is executed by the physics engine.
  84942. */
  84943. this.beforeStep = function () {
  84944. if (!_this._physicsEngine) {
  84945. return;
  84946. }
  84947. _this.object.translate(_this._deltaPosition, -1);
  84948. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84949. _this.object.computeWorldMatrix(false);
  84950. if (_this.object.parent && _this.object.rotationQuaternion) {
  84951. _this.getParentsRotation();
  84952. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84953. }
  84954. else {
  84955. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84956. }
  84957. if (!_this._options.disableBidirectionalTransformation) {
  84958. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84959. }
  84960. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84961. func(_this);
  84962. });
  84963. };
  84964. /**
  84965. * this function is executed by the physics engine.
  84966. */
  84967. this.afterStep = function () {
  84968. if (!_this._physicsEngine) {
  84969. return;
  84970. }
  84971. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84972. func(_this);
  84973. });
  84974. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84975. // object has now its world rotation. needs to be converted to local.
  84976. if (_this.object.parent && _this.object.rotationQuaternion) {
  84977. _this.getParentsRotation();
  84978. _this._tmpQuat.conjugateInPlace();
  84979. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84980. }
  84981. // take the position set and make it the absolute position of this object.
  84982. _this.object.setAbsolutePosition(_this.object.position);
  84983. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84984. _this.object.translate(_this._deltaPosition, 1);
  84985. };
  84986. /**
  84987. * Legacy collision detection event support
  84988. */
  84989. this.onCollideEvent = null;
  84990. //event and body object due to cannon's event-based architecture.
  84991. this.onCollide = function (e) {
  84992. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84993. return;
  84994. }
  84995. if (!_this._physicsEngine) {
  84996. return;
  84997. }
  84998. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84999. if (otherImpostor) {
  85000. // Legacy collision detection event support
  85001. if (_this.onCollideEvent) {
  85002. _this.onCollideEvent(_this, otherImpostor);
  85003. }
  85004. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  85005. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  85006. }).forEach(function (obj) {
  85007. obj.callback(_this, otherImpostor);
  85008. });
  85009. }
  85010. };
  85011. //sanity check!
  85012. if (!this.object) {
  85013. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  85014. return;
  85015. }
  85016. //legacy support for old syntax.
  85017. if (!this._scene && object.getScene) {
  85018. this._scene = object.getScene();
  85019. }
  85020. if (!this._scene) {
  85021. return;
  85022. }
  85023. this._physicsEngine = this._scene.getPhysicsEngine();
  85024. if (!this._physicsEngine) {
  85025. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  85026. }
  85027. else {
  85028. //set the object's quaternion, if not set
  85029. if (!this.object.rotationQuaternion) {
  85030. if (this.object.rotation) {
  85031. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  85032. }
  85033. else {
  85034. this.object.rotationQuaternion = new BABYLON.Quaternion();
  85035. }
  85036. }
  85037. //default options params
  85038. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  85039. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  85040. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  85041. this._joints = [];
  85042. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  85043. if (!this.object.parent || this._options.ignoreParent) {
  85044. this._init();
  85045. }
  85046. else if (this.object.parent.physicsImpostor) {
  85047. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  85048. }
  85049. }
  85050. }
  85051. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  85052. get: function () {
  85053. return this._isDisposed;
  85054. },
  85055. enumerable: true,
  85056. configurable: true
  85057. });
  85058. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  85059. get: function () {
  85060. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  85061. },
  85062. set: function (value) {
  85063. this.setMass(value);
  85064. },
  85065. enumerable: true,
  85066. configurable: true
  85067. });
  85068. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  85069. get: function () {
  85070. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  85071. },
  85072. set: function (value) {
  85073. if (!this._physicsEngine) {
  85074. return;
  85075. }
  85076. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  85077. },
  85078. enumerable: true,
  85079. configurable: true
  85080. });
  85081. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  85082. get: function () {
  85083. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  85084. },
  85085. set: function (value) {
  85086. if (!this._physicsEngine) {
  85087. return;
  85088. }
  85089. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  85090. },
  85091. enumerable: true,
  85092. configurable: true
  85093. });
  85094. /**
  85095. * This function will completly initialize this impostor.
  85096. * It will create a new body - but only if this mesh has no parent.
  85097. * If it has, this impostor will not be used other than to define the impostor
  85098. * of the child mesh.
  85099. */
  85100. PhysicsImpostor.prototype._init = function () {
  85101. if (!this._physicsEngine) {
  85102. return;
  85103. }
  85104. this._physicsEngine.removeImpostor(this);
  85105. this.physicsBody = null;
  85106. this._parent = this._parent || this._getPhysicsParent();
  85107. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  85108. this._physicsEngine.addImpostor(this);
  85109. }
  85110. };
  85111. PhysicsImpostor.prototype._getPhysicsParent = function () {
  85112. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  85113. var parentMesh = this.object.parent;
  85114. return parentMesh.physicsImpostor;
  85115. }
  85116. return null;
  85117. };
  85118. /**
  85119. * Should a new body be generated.
  85120. */
  85121. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  85122. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  85123. };
  85124. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  85125. this.forceUpdate();
  85126. };
  85127. /**
  85128. * Force a regeneration of this or the parent's impostor's body.
  85129. * Use under cautious - This will remove all joints already implemented.
  85130. */
  85131. PhysicsImpostor.prototype.forceUpdate = function () {
  85132. this._init();
  85133. if (this.parent && !this._options.ignoreParent) {
  85134. this.parent.forceUpdate();
  85135. }
  85136. };
  85137. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  85138. /*public get mesh(): AbstractMesh {
  85139. return this._mesh;
  85140. }*/
  85141. /**
  85142. * Gets the body that holds this impostor. Either its own, or its parent.
  85143. */
  85144. get: function () {
  85145. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  85146. },
  85147. /**
  85148. * Set the physics body. Used mainly by the physics engine/plugin
  85149. */
  85150. set: function (physicsBody) {
  85151. if (this._physicsBody && this._physicsEngine) {
  85152. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  85153. }
  85154. this._physicsBody = physicsBody;
  85155. this.resetUpdateFlags();
  85156. },
  85157. enumerable: true,
  85158. configurable: true
  85159. });
  85160. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  85161. get: function () {
  85162. return !this._options.ignoreParent && this._parent ? this._parent : null;
  85163. },
  85164. set: function (value) {
  85165. this._parent = value;
  85166. },
  85167. enumerable: true,
  85168. configurable: true
  85169. });
  85170. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  85171. this._bodyUpdateRequired = false;
  85172. };
  85173. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  85174. if (this.object.getBoundingInfo) {
  85175. var q = this.object.rotationQuaternion;
  85176. //reset rotation
  85177. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  85178. //calculate the world matrix with no rotation
  85179. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85180. var boundingInfo = this.object.getBoundingInfo();
  85181. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  85182. //bring back the rotation
  85183. this.object.rotationQuaternion = q;
  85184. //calculate the world matrix with the new rotation
  85185. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85186. return size;
  85187. }
  85188. else {
  85189. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  85190. }
  85191. };
  85192. PhysicsImpostor.prototype.getObjectCenter = function () {
  85193. if (this.object.getBoundingInfo) {
  85194. var boundingInfo = this.object.getBoundingInfo();
  85195. return boundingInfo.boundingBox.centerWorld;
  85196. }
  85197. else {
  85198. return this.object.position;
  85199. }
  85200. };
  85201. /**
  85202. * Get a specific parametes from the options parameter.
  85203. */
  85204. PhysicsImpostor.prototype.getParam = function (paramName) {
  85205. return this._options[paramName];
  85206. };
  85207. /**
  85208. * Sets a specific parameter in the options given to the physics plugin
  85209. */
  85210. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85211. this._options[paramName] = value;
  85212. this._bodyUpdateRequired = true;
  85213. };
  85214. /**
  85215. * Specifically change the body's mass option. Won't recreate the physics body object
  85216. */
  85217. PhysicsImpostor.prototype.setMass = function (mass) {
  85218. if (this.getParam("mass") !== mass) {
  85219. this.setParam("mass", mass);
  85220. }
  85221. if (this._physicsEngine) {
  85222. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85223. }
  85224. };
  85225. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85226. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85227. };
  85228. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85229. if (this._physicsEngine) {
  85230. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  85231. }
  85232. };
  85233. PhysicsImpostor.prototype.getAngularVelocity = function () {
  85234. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  85235. };
  85236. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  85237. if (this._physicsEngine) {
  85238. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  85239. }
  85240. };
  85241. /**
  85242. * Execute a function with the physics plugin native code.
  85243. * Provide a function the will have two variables - the world object and the physics body object.
  85244. */
  85245. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  85246. if (this._physicsEngine) {
  85247. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  85248. }
  85249. };
  85250. /**
  85251. * Register a function that will be executed before the physics world is stepping forward.
  85252. */
  85253. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  85254. this._onBeforePhysicsStepCallbacks.push(func);
  85255. };
  85256. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  85257. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  85258. if (index > -1) {
  85259. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  85260. }
  85261. else {
  85262. BABYLON.Tools.Warn("Function to remove was not found");
  85263. }
  85264. };
  85265. /**
  85266. * Register a function that will be executed after the physics step
  85267. */
  85268. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  85269. this._onAfterPhysicsStepCallbacks.push(func);
  85270. };
  85271. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  85272. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  85273. if (index > -1) {
  85274. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  85275. }
  85276. else {
  85277. BABYLON.Tools.Warn("Function to remove was not found");
  85278. }
  85279. };
  85280. /**
  85281. * register a function that will be executed when this impostor collides against a different body.
  85282. */
  85283. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85284. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85285. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85286. };
  85287. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85288. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85289. var index = -1;
  85290. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85291. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85292. // chcek the arrays match
  85293. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85294. return collidedAgainstList.indexOf(impostor) > -1;
  85295. });
  85296. if (sameList) {
  85297. index = idx;
  85298. }
  85299. return sameList;
  85300. }
  85301. return false;
  85302. });
  85303. if (found) {
  85304. this._onPhysicsCollideCallbacks.splice(index, 1);
  85305. }
  85306. else {
  85307. BABYLON.Tools.Warn("Function to remove was not found");
  85308. }
  85309. };
  85310. PhysicsImpostor.prototype.getParentsRotation = function () {
  85311. var parent = this.object.parent;
  85312. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85313. while (parent) {
  85314. if (parent.rotationQuaternion) {
  85315. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85316. }
  85317. else {
  85318. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85319. }
  85320. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85321. parent = parent.parent;
  85322. }
  85323. return this._tmpQuat;
  85324. };
  85325. /**
  85326. * Apply a force
  85327. */
  85328. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85329. if (this._physicsEngine) {
  85330. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85331. }
  85332. return this;
  85333. };
  85334. /**
  85335. * Apply an impulse
  85336. */
  85337. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85338. if (this._physicsEngine) {
  85339. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85340. }
  85341. return this;
  85342. };
  85343. /**
  85344. * A help function to create a joint.
  85345. */
  85346. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85347. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85348. this.addJoint(otherImpostor, joint);
  85349. return this;
  85350. };
  85351. /**
  85352. * Add a joint to this impostor with a different impostor.
  85353. */
  85354. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85355. this._joints.push({
  85356. otherImpostor: otherImpostor,
  85357. joint: joint
  85358. });
  85359. if (this._physicsEngine) {
  85360. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85361. }
  85362. return this;
  85363. };
  85364. /**
  85365. * Will keep this body still, in a sleep mode.
  85366. */
  85367. PhysicsImpostor.prototype.sleep = function () {
  85368. if (this._physicsEngine) {
  85369. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85370. }
  85371. return this;
  85372. };
  85373. /**
  85374. * Wake the body up.
  85375. */
  85376. PhysicsImpostor.prototype.wakeUp = function () {
  85377. if (this._physicsEngine) {
  85378. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85379. }
  85380. return this;
  85381. };
  85382. PhysicsImpostor.prototype.clone = function (newObject) {
  85383. if (!newObject)
  85384. return null;
  85385. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85386. };
  85387. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85388. var _this = this;
  85389. //no dispose if no physics engine is available.
  85390. if (!this._physicsEngine) {
  85391. return;
  85392. }
  85393. this._joints.forEach(function (j) {
  85394. if (_this._physicsEngine) {
  85395. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85396. }
  85397. });
  85398. //dispose the physics body
  85399. this._physicsEngine.removeImpostor(this);
  85400. if (this.parent) {
  85401. this.parent.forceUpdate();
  85402. }
  85403. else {
  85404. /*this._object.getChildMeshes().forEach(function(mesh) {
  85405. if (mesh.physicsImpostor) {
  85406. if (disposeChildren) {
  85407. mesh.physicsImpostor.dispose();
  85408. mesh.physicsImpostor = null;
  85409. }
  85410. }
  85411. })*/
  85412. }
  85413. this._isDisposed = true;
  85414. };
  85415. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85416. this._deltaPosition.copyFrom(position);
  85417. };
  85418. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85419. if (!this._deltaRotation) {
  85420. this._deltaRotation = new BABYLON.Quaternion();
  85421. }
  85422. this._deltaRotation.copyFrom(rotation);
  85423. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85424. };
  85425. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85426. if (this._physicsEngine) {
  85427. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85428. }
  85429. return this;
  85430. };
  85431. PhysicsImpostor.prototype.getRadius = function () {
  85432. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85433. };
  85434. /**
  85435. * Sync a bone with this impostor
  85436. * @param bone The bone to sync to the impostor.
  85437. * @param boneMesh The mesh that the bone is influencing.
  85438. * @param jointPivot The pivot of the joint / bone in local space.
  85439. * @param distToJoint Optional distance from the impostor to the joint.
  85440. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85441. */
  85442. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85443. var tempVec = PhysicsImpostor._tmpVecs[0];
  85444. var mesh = this.object;
  85445. if (mesh.rotationQuaternion) {
  85446. if (adjustRotation) {
  85447. var tempQuat = PhysicsImpostor._tmpQuat;
  85448. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85449. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85450. }
  85451. else {
  85452. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85453. }
  85454. }
  85455. tempVec.x = 0;
  85456. tempVec.y = 0;
  85457. tempVec.z = 0;
  85458. if (jointPivot) {
  85459. tempVec.x = jointPivot.x;
  85460. tempVec.y = jointPivot.y;
  85461. tempVec.z = jointPivot.z;
  85462. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85463. if (distToJoint === undefined || distToJoint === null) {
  85464. distToJoint = jointPivot.length();
  85465. }
  85466. tempVec.x *= distToJoint;
  85467. tempVec.y *= distToJoint;
  85468. tempVec.z *= distToJoint;
  85469. }
  85470. if (bone.getParent()) {
  85471. tempVec.addInPlace(mesh.getAbsolutePosition());
  85472. bone.setAbsolutePosition(tempVec, boneMesh);
  85473. }
  85474. else {
  85475. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85476. boneMesh.position.x -= tempVec.x;
  85477. boneMesh.position.y -= tempVec.y;
  85478. boneMesh.position.z -= tempVec.z;
  85479. }
  85480. };
  85481. /**
  85482. * Sync impostor to a bone
  85483. * @param bone The bone that the impostor will be synced to.
  85484. * @param boneMesh The mesh that the bone is influencing.
  85485. * @param jointPivot The pivot of the joint / bone in local space.
  85486. * @param distToJoint Optional distance from the impostor to the joint.
  85487. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85488. * @param boneAxis Optional vector3 axis the bone is aligned with
  85489. */
  85490. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85491. var mesh = this.object;
  85492. if (mesh.rotationQuaternion) {
  85493. if (adjustRotation) {
  85494. var tempQuat = PhysicsImpostor._tmpQuat;
  85495. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85496. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85497. }
  85498. else {
  85499. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85500. }
  85501. }
  85502. var pos = PhysicsImpostor._tmpVecs[0];
  85503. var boneDir = PhysicsImpostor._tmpVecs[1];
  85504. if (!boneAxis) {
  85505. boneAxis = PhysicsImpostor._tmpVecs[2];
  85506. boneAxis.x = 0;
  85507. boneAxis.y = 1;
  85508. boneAxis.z = 0;
  85509. }
  85510. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85511. bone.getAbsolutePositionToRef(boneMesh, pos);
  85512. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85513. distToJoint = jointPivot.length();
  85514. }
  85515. if (distToJoint !== undefined && distToJoint !== null) {
  85516. pos.x += boneDir.x * distToJoint;
  85517. pos.y += boneDir.y * distToJoint;
  85518. pos.z += boneDir.z * distToJoint;
  85519. }
  85520. mesh.setAbsolutePosition(pos);
  85521. };
  85522. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85523. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85524. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85525. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85526. //Impostor types
  85527. PhysicsImpostor.NoImpostor = 0;
  85528. PhysicsImpostor.SphereImpostor = 1;
  85529. PhysicsImpostor.BoxImpostor = 2;
  85530. PhysicsImpostor.PlaneImpostor = 3;
  85531. PhysicsImpostor.MeshImpostor = 4;
  85532. PhysicsImpostor.CylinderImpostor = 7;
  85533. PhysicsImpostor.ParticleImpostor = 8;
  85534. PhysicsImpostor.HeightmapImpostor = 9;
  85535. return PhysicsImpostor;
  85536. }());
  85537. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85538. })(BABYLON || (BABYLON = {}));
  85539. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85540. var BABYLON;
  85541. (function (BABYLON) {
  85542. var PhysicsEngine = /** @class */ (function () {
  85543. function PhysicsEngine(gravity, _physicsPlugin) {
  85544. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85545. this._physicsPlugin = _physicsPlugin;
  85546. //new methods and parameters
  85547. this._impostors = [];
  85548. this._joints = [];
  85549. if (!this._physicsPlugin.isSupported()) {
  85550. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85551. + "Please make sure it is included.");
  85552. }
  85553. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85554. this.setGravity(gravity);
  85555. this.setTimeStep();
  85556. }
  85557. PhysicsEngine.prototype.setGravity = function (gravity) {
  85558. this.gravity = gravity;
  85559. this._physicsPlugin.setGravity(this.gravity);
  85560. };
  85561. /**
  85562. * Set the time step of the physics engine.
  85563. * default is 1/60.
  85564. * To slow it down, enter 1/600 for example.
  85565. * To speed it up, 1/30
  85566. * @param {number} newTimeStep the new timestep to apply to this world.
  85567. */
  85568. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85569. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85570. this._physicsPlugin.setTimeStep(newTimeStep);
  85571. };
  85572. /**
  85573. * Get the time step of the physics engine.
  85574. */
  85575. PhysicsEngine.prototype.getTimeStep = function () {
  85576. return this._physicsPlugin.getTimeStep();
  85577. };
  85578. PhysicsEngine.prototype.dispose = function () {
  85579. this._impostors.forEach(function (impostor) {
  85580. impostor.dispose();
  85581. });
  85582. this._physicsPlugin.dispose();
  85583. };
  85584. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85585. return this._physicsPlugin.name;
  85586. };
  85587. /**
  85588. * Adding a new impostor for the impostor tracking.
  85589. * This will be done by the impostor itself.
  85590. * @param {PhysicsImpostor} impostor the impostor to add
  85591. */
  85592. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85593. impostor.uniqueId = this._impostors.push(impostor);
  85594. //if no parent, generate the body
  85595. if (!impostor.parent) {
  85596. this._physicsPlugin.generatePhysicsBody(impostor);
  85597. }
  85598. };
  85599. /**
  85600. * Remove an impostor from the engine.
  85601. * This impostor and its mesh will not longer be updated by the physics engine.
  85602. * @param {PhysicsImpostor} impostor the impostor to remove
  85603. */
  85604. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85605. var index = this._impostors.indexOf(impostor);
  85606. if (index > -1) {
  85607. var removed = this._impostors.splice(index, 1);
  85608. //Is it needed?
  85609. if (removed.length) {
  85610. //this will also remove it from the world.
  85611. removed[0].physicsBody = null;
  85612. }
  85613. }
  85614. };
  85615. /**
  85616. * Add a joint to the physics engine
  85617. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85618. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85619. * @param {PhysicsJoint} the joint that will connect both impostors.
  85620. */
  85621. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85622. var impostorJoint = {
  85623. mainImpostor: mainImpostor,
  85624. connectedImpostor: connectedImpostor,
  85625. joint: joint
  85626. };
  85627. joint.physicsPlugin = this._physicsPlugin;
  85628. this._joints.push(impostorJoint);
  85629. this._physicsPlugin.generateJoint(impostorJoint);
  85630. };
  85631. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85632. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85633. return (impostorJoint.connectedImpostor === connectedImpostor
  85634. && impostorJoint.joint === joint
  85635. && impostorJoint.mainImpostor === mainImpostor);
  85636. });
  85637. if (matchingJoints.length) {
  85638. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85639. //TODO remove it from the list as well
  85640. }
  85641. };
  85642. /**
  85643. * Called by the scene. no need to call it.
  85644. */
  85645. PhysicsEngine.prototype._step = function (delta) {
  85646. var _this = this;
  85647. //check if any mesh has no body / requires an update
  85648. this._impostors.forEach(function (impostor) {
  85649. if (impostor.isBodyInitRequired()) {
  85650. _this._physicsPlugin.generatePhysicsBody(impostor);
  85651. }
  85652. });
  85653. if (delta > 0.1) {
  85654. delta = 0.1;
  85655. }
  85656. else if (delta <= 0) {
  85657. delta = 1.0 / 60.0;
  85658. }
  85659. this._physicsPlugin.executeStep(delta, this._impostors);
  85660. };
  85661. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85662. return this._physicsPlugin;
  85663. };
  85664. PhysicsEngine.prototype.getImpostors = function () {
  85665. return this._impostors;
  85666. };
  85667. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85668. for (var i = 0; i < this._impostors.length; ++i) {
  85669. if (this._impostors[i].object === object) {
  85670. return this._impostors[i];
  85671. }
  85672. }
  85673. return null;
  85674. };
  85675. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85676. for (var i = 0; i < this._impostors.length; ++i) {
  85677. if (this._impostors[i].physicsBody === body) {
  85678. return this._impostors[i];
  85679. }
  85680. }
  85681. return null;
  85682. };
  85683. // Statics
  85684. PhysicsEngine.Epsilon = 0.001;
  85685. return PhysicsEngine;
  85686. }());
  85687. BABYLON.PhysicsEngine = PhysicsEngine;
  85688. })(BABYLON || (BABYLON = {}));
  85689. //# sourceMappingURL=babylon.physicsEngine.js.map
  85690. var BABYLON;
  85691. (function (BABYLON) {
  85692. var PhysicsHelper = /** @class */ (function () {
  85693. function PhysicsHelper(scene) {
  85694. this._scene = scene;
  85695. this._physicsEngine = this._scene.getPhysicsEngine();
  85696. if (!this._physicsEngine) {
  85697. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85698. }
  85699. }
  85700. /**
  85701. * @param {Vector3} origin the origin of the explosion
  85702. * @param {number} radius the explosion radius
  85703. * @param {number} strength the explosion strength
  85704. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85705. */
  85706. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85707. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85708. if (!this._physicsEngine) {
  85709. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85710. return null;
  85711. }
  85712. var impostors = this._physicsEngine.getImpostors();
  85713. if (impostors.length === 0) {
  85714. return null;
  85715. }
  85716. var event = new PhysicsRadialExplosionEvent(this._scene);
  85717. impostors.forEach(function (impostor) {
  85718. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85719. if (!impostorForceAndContactPoint) {
  85720. return;
  85721. }
  85722. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85723. });
  85724. event.dispose(false);
  85725. return event;
  85726. };
  85727. /**
  85728. * @param {Vector3} origin the origin of the explosion
  85729. * @param {number} radius the explosion radius
  85730. * @param {number} strength the explosion strength
  85731. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85732. */
  85733. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85734. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85735. if (!this._physicsEngine) {
  85736. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85737. return null;
  85738. }
  85739. var impostors = this._physicsEngine.getImpostors();
  85740. if (impostors.length === 0) {
  85741. return null;
  85742. }
  85743. var event = new PhysicsRadialExplosionEvent(this._scene);
  85744. impostors.forEach(function (impostor) {
  85745. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85746. if (!impostorForceAndContactPoint) {
  85747. return;
  85748. }
  85749. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85750. });
  85751. event.dispose(false);
  85752. return event;
  85753. };
  85754. /**
  85755. * @param {Vector3} origin the origin of the explosion
  85756. * @param {number} radius the explosion radius
  85757. * @param {number} strength the explosion strength
  85758. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85759. */
  85760. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85761. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85762. if (!this._physicsEngine) {
  85763. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85764. return null;
  85765. }
  85766. var impostors = this._physicsEngine.getImpostors();
  85767. if (impostors.length === 0) {
  85768. return null;
  85769. }
  85770. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85771. event.dispose(false);
  85772. return event;
  85773. };
  85774. /**
  85775. * @param {Vector3} origin the origin of the updraft
  85776. * @param {number} radius the radius of the updraft
  85777. * @param {number} strength the strength of the updraft
  85778. * @param {number} height the height of the updraft
  85779. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85780. */
  85781. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85782. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85783. if (!this._physicsEngine) {
  85784. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85785. return null;
  85786. }
  85787. if (this._physicsEngine.getImpostors().length === 0) {
  85788. return null;
  85789. }
  85790. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85791. event.dispose(false);
  85792. return event;
  85793. };
  85794. /**
  85795. * @param {Vector3} origin the of the vortex
  85796. * @param {number} radius the radius of the vortex
  85797. * @param {number} strength the strength of the vortex
  85798. * @param {number} height the height of the vortex
  85799. */
  85800. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85801. if (!this._physicsEngine) {
  85802. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85803. return null;
  85804. }
  85805. if (this._physicsEngine.getImpostors().length === 0) {
  85806. return null;
  85807. }
  85808. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85809. event.dispose(false);
  85810. return event;
  85811. };
  85812. return PhysicsHelper;
  85813. }());
  85814. BABYLON.PhysicsHelper = PhysicsHelper;
  85815. /***** Radial explosion *****/
  85816. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85817. function PhysicsRadialExplosionEvent(scene) {
  85818. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85819. this._rays = [];
  85820. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85821. this._scene = scene;
  85822. }
  85823. /**
  85824. * Returns the data related to the radial explosion event (sphere & rays).
  85825. * @returns {PhysicsRadialExplosionEventData}
  85826. */
  85827. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85828. this._dataFetched = true;
  85829. return {
  85830. sphere: this._sphere,
  85831. rays: this._rays,
  85832. };
  85833. };
  85834. /**
  85835. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85836. * @param impostor
  85837. * @param {Vector3} origin the origin of the explosion
  85838. * @param {number} radius the explosion radius
  85839. * @param {number} strength the explosion strength
  85840. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85841. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85842. */
  85843. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85844. if (impostor.mass === 0) {
  85845. return null;
  85846. }
  85847. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85848. return null;
  85849. }
  85850. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85851. return null;
  85852. }
  85853. var impostorObjectCenter = impostor.getObjectCenter();
  85854. var direction = impostorObjectCenter.subtract(origin);
  85855. var ray = new BABYLON.Ray(origin, direction, radius);
  85856. this._rays.push(ray);
  85857. var hit = ray.intersectsMesh(impostor.object);
  85858. var contactPoint = hit.pickedPoint;
  85859. if (!contactPoint) {
  85860. return null;
  85861. }
  85862. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85863. if (distanceFromOrigin > radius) {
  85864. return null;
  85865. }
  85866. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85867. ? strength
  85868. : strength * (1 - (distanceFromOrigin / radius));
  85869. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85870. return { force: force, contactPoint: contactPoint };
  85871. };
  85872. /**
  85873. * Disposes the sphere.
  85874. * @param {bolean} force
  85875. */
  85876. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85877. var _this = this;
  85878. if (force === void 0) { force = true; }
  85879. if (force) {
  85880. this._sphere.dispose();
  85881. }
  85882. else {
  85883. setTimeout(function () {
  85884. if (!_this._dataFetched) {
  85885. _this._sphere.dispose();
  85886. }
  85887. }, 0);
  85888. }
  85889. };
  85890. /*** Helpers ***/
  85891. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85892. if (!this._sphere) {
  85893. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85894. this._sphere.isVisible = false;
  85895. }
  85896. };
  85897. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85898. var impostorObject = impostor.object;
  85899. this._prepareSphere();
  85900. this._sphere.position = origin;
  85901. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85902. this._sphere._updateBoundingInfo();
  85903. this._sphere.computeWorldMatrix(true);
  85904. return this._sphere.intersectsMesh(impostorObject, true);
  85905. };
  85906. return PhysicsRadialExplosionEvent;
  85907. }());
  85908. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85909. /***** Gravitational Field *****/
  85910. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85911. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85912. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85913. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85914. this._physicsHelper = physicsHelper;
  85915. this._scene = scene;
  85916. this._origin = origin;
  85917. this._radius = radius;
  85918. this._strength = strength;
  85919. this._falloff = falloff;
  85920. this._tickCallback = this._tick.bind(this);
  85921. }
  85922. /**
  85923. * Returns the data related to the gravitational field event (sphere).
  85924. * @returns {PhysicsGravitationalFieldEventData}
  85925. */
  85926. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85927. this._dataFetched = true;
  85928. return {
  85929. sphere: this._sphere,
  85930. };
  85931. };
  85932. /**
  85933. * Enables the gravitational field.
  85934. */
  85935. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85936. this._tickCallback.call(this);
  85937. this._scene.registerBeforeRender(this._tickCallback);
  85938. };
  85939. /**
  85940. * Disables the gravitational field.
  85941. */
  85942. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85943. this._scene.unregisterBeforeRender(this._tickCallback);
  85944. };
  85945. /**
  85946. * Disposes the sphere.
  85947. * @param {bolean} force
  85948. */
  85949. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85950. var _this = this;
  85951. if (force === void 0) { force = true; }
  85952. if (force) {
  85953. this._sphere.dispose();
  85954. }
  85955. else {
  85956. setTimeout(function () {
  85957. if (!_this._dataFetched) {
  85958. _this._sphere.dispose();
  85959. }
  85960. }, 0);
  85961. }
  85962. };
  85963. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85964. // Since the params won't change, we fetch the event only once
  85965. if (this._sphere) {
  85966. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85967. }
  85968. else {
  85969. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85970. if (radialExplosionEvent) {
  85971. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85972. }
  85973. }
  85974. };
  85975. return PhysicsGravitationalFieldEvent;
  85976. }());
  85977. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85978. /***** Updraft *****/
  85979. var PhysicsUpdraftEvent = /** @class */ (function () {
  85980. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85981. this._scene = _scene;
  85982. this._origin = _origin;
  85983. this._radius = _radius;
  85984. this._strength = _strength;
  85985. this._height = _height;
  85986. this._updraftMode = _updraftMode;
  85987. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85988. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85989. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85990. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85991. this._physicsEngine = this._scene.getPhysicsEngine();
  85992. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85993. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85994. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85995. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85996. }
  85997. this._tickCallback = this._tick.bind(this);
  85998. }
  85999. /**
  86000. * Returns the data related to the updraft event (cylinder).
  86001. * @returns {PhysicsUpdraftEventData}
  86002. */
  86003. PhysicsUpdraftEvent.prototype.getData = function () {
  86004. this._dataFetched = true;
  86005. return {
  86006. cylinder: this._cylinder,
  86007. };
  86008. };
  86009. /**
  86010. * Enables the updraft.
  86011. */
  86012. PhysicsUpdraftEvent.prototype.enable = function () {
  86013. this._tickCallback.call(this);
  86014. this._scene.registerBeforeRender(this._tickCallback);
  86015. };
  86016. /**
  86017. * Disables the cortex.
  86018. */
  86019. PhysicsUpdraftEvent.prototype.disable = function () {
  86020. this._scene.unregisterBeforeRender(this._tickCallback);
  86021. };
  86022. /**
  86023. * Disposes the sphere.
  86024. * @param {bolean} force
  86025. */
  86026. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  86027. var _this = this;
  86028. if (force === void 0) { force = true; }
  86029. if (force) {
  86030. this._cylinder.dispose();
  86031. }
  86032. else {
  86033. setTimeout(function () {
  86034. if (!_this._dataFetched) {
  86035. _this._cylinder.dispose();
  86036. }
  86037. }, 0);
  86038. }
  86039. };
  86040. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86041. if (impostor.mass === 0) {
  86042. return null;
  86043. }
  86044. if (!this._intersectsWithCylinder(impostor)) {
  86045. return null;
  86046. }
  86047. var impostorObjectCenter = impostor.getObjectCenter();
  86048. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86049. var direction = this._originDirection;
  86050. }
  86051. else {
  86052. var direction = impostorObjectCenter.subtract(this._originTop);
  86053. }
  86054. var multiplier = this._strength * -1;
  86055. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86056. return { force: force, contactPoint: impostorObjectCenter };
  86057. };
  86058. PhysicsUpdraftEvent.prototype._tick = function () {
  86059. var _this = this;
  86060. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86061. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86062. if (!impostorForceAndContactPoint) {
  86063. return;
  86064. }
  86065. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86066. });
  86067. };
  86068. /*** Helpers ***/
  86069. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  86070. if (!this._cylinder) {
  86071. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  86072. height: this._height,
  86073. diameter: this._radius * 2,
  86074. }, this._scene);
  86075. this._cylinder.isVisible = false;
  86076. }
  86077. };
  86078. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  86079. var impostorObject = impostor.object;
  86080. this._prepareCylinder();
  86081. this._cylinder.position = this._cylinderPosition;
  86082. return this._cylinder.intersectsMesh(impostorObject, true);
  86083. };
  86084. return PhysicsUpdraftEvent;
  86085. }());
  86086. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  86087. /***** Vortex *****/
  86088. var PhysicsVortexEvent = /** @class */ (function () {
  86089. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  86090. this._scene = _scene;
  86091. this._origin = _origin;
  86092. this._radius = _radius;
  86093. this._strength = _strength;
  86094. this._height = _height;
  86095. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86096. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  86097. this._updraftMultiplier = 0.02;
  86098. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86099. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86100. this._physicsEngine = this._scene.getPhysicsEngine();
  86101. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86102. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86103. this._tickCallback = this._tick.bind(this);
  86104. }
  86105. /**
  86106. * Returns the data related to the vortex event (cylinder).
  86107. * @returns {PhysicsVortexEventData}
  86108. */
  86109. PhysicsVortexEvent.prototype.getData = function () {
  86110. this._dataFetched = true;
  86111. return {
  86112. cylinder: this._cylinder,
  86113. };
  86114. };
  86115. /**
  86116. * Enables the vortex.
  86117. */
  86118. PhysicsVortexEvent.prototype.enable = function () {
  86119. this._tickCallback.call(this);
  86120. this._scene.registerBeforeRender(this._tickCallback);
  86121. };
  86122. /**
  86123. * Disables the cortex.
  86124. */
  86125. PhysicsVortexEvent.prototype.disable = function () {
  86126. this._scene.unregisterBeforeRender(this._tickCallback);
  86127. };
  86128. /**
  86129. * Disposes the sphere.
  86130. * @param {bolean} force
  86131. */
  86132. PhysicsVortexEvent.prototype.dispose = function (force) {
  86133. var _this = this;
  86134. if (force === void 0) { force = true; }
  86135. if (force) {
  86136. this._cylinder.dispose();
  86137. }
  86138. else {
  86139. setTimeout(function () {
  86140. if (!_this._dataFetched) {
  86141. _this._cylinder.dispose();
  86142. }
  86143. }, 0);
  86144. }
  86145. };
  86146. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86147. if (impostor.mass === 0) {
  86148. return null;
  86149. }
  86150. if (!this._intersectsWithCylinder(impostor)) {
  86151. return null;
  86152. }
  86153. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86154. return null;
  86155. }
  86156. var impostorObjectCenter = impostor.getObjectCenter();
  86157. 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)
  86158. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  86159. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  86160. var hit = ray.intersectsMesh(impostor.object);
  86161. var contactPoint = hit.pickedPoint;
  86162. if (!contactPoint) {
  86163. return null;
  86164. }
  86165. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  86166. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  86167. var directionToOrigin = contactPoint.normalize();
  86168. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86169. directionToOrigin = directionToOrigin.negate();
  86170. }
  86171. // TODO: find a more physically based solution
  86172. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86173. var forceX = directionToOrigin.x * this._strength / 8;
  86174. var forceY = directionToOrigin.y * this._updraftMultiplier;
  86175. var forceZ = directionToOrigin.z * this._strength / 8;
  86176. }
  86177. else {
  86178. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  86179. var forceY = this._originTop.y * this._updraftMultiplier;
  86180. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  86181. }
  86182. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  86183. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  86184. return { force: force, contactPoint: impostorObjectCenter };
  86185. };
  86186. PhysicsVortexEvent.prototype._tick = function () {
  86187. var _this = this;
  86188. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86189. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86190. if (!impostorForceAndContactPoint) {
  86191. return;
  86192. }
  86193. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86194. });
  86195. };
  86196. /*** Helpers ***/
  86197. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86198. if (!this._cylinder) {
  86199. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86200. height: this._height,
  86201. diameter: this._radius * 2,
  86202. }, this._scene);
  86203. this._cylinder.isVisible = false;
  86204. }
  86205. };
  86206. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86207. var impostorObject = impostor.object;
  86208. this._prepareCylinder();
  86209. this._cylinder.position = this._cylinderPosition;
  86210. return this._cylinder.intersectsMesh(impostorObject, true);
  86211. };
  86212. return PhysicsVortexEvent;
  86213. }());
  86214. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86215. /***** Enums *****/
  86216. /**
  86217. * The strenght of the force in correspondence to the distance of the affected object
  86218. */
  86219. var PhysicsRadialImpulseFalloff;
  86220. (function (PhysicsRadialImpulseFalloff) {
  86221. /** Defines that impulse is constant in strength across it's whole radius */
  86222. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86223. /** DEfines that impulse gets weaker if it's further from the origin */
  86224. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86225. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86226. /**
  86227. * The strenght of the force in correspondence to the distance of the affected object
  86228. */
  86229. var PhysicsUpdraftMode;
  86230. (function (PhysicsUpdraftMode) {
  86231. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  86232. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  86233. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  86234. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  86235. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  86236. })(BABYLON || (BABYLON = {}));
  86237. //# sourceMappingURL=babylon.physicsHelper.js.map
  86238. var BABYLON;
  86239. (function (BABYLON) {
  86240. var CannonJSPlugin = /** @class */ (function () {
  86241. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  86242. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  86243. if (iterations === void 0) { iterations = 10; }
  86244. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  86245. this.name = "CannonJSPlugin";
  86246. this._physicsMaterials = new Array();
  86247. this._fixedTimeStep = 1 / 60;
  86248. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  86249. this.BJSCANNON = CANNON;
  86250. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  86251. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  86252. this._tmpPosition = BABYLON.Vector3.Zero();
  86253. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  86254. this._tmpUnityRotation = new BABYLON.Quaternion();
  86255. if (!this.isSupported()) {
  86256. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  86257. return;
  86258. }
  86259. this._extendNamespace();
  86260. this.world = new this.BJSCANNON.World();
  86261. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  86262. this.world.solver.iterations = iterations;
  86263. }
  86264. CannonJSPlugin.prototype.setGravity = function (gravity) {
  86265. this.world.gravity.copy(gravity);
  86266. };
  86267. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  86268. this._fixedTimeStep = timeStep;
  86269. };
  86270. CannonJSPlugin.prototype.getTimeStep = function () {
  86271. return this._fixedTimeStep;
  86272. };
  86273. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  86274. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  86275. };
  86276. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86277. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86278. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86279. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  86280. };
  86281. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86282. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86283. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86284. impostor.physicsBody.applyForce(impulse, worldPoint);
  86285. };
  86286. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86287. //parent-child relationship. Does this impostor has a parent impostor?
  86288. if (impostor.parent) {
  86289. if (impostor.physicsBody) {
  86290. this.removePhysicsBody(impostor);
  86291. //TODO is that needed?
  86292. impostor.forceUpdate();
  86293. }
  86294. return;
  86295. }
  86296. //should a new body be created for this impostor?
  86297. if (impostor.isBodyInitRequired()) {
  86298. var shape = this._createShape(impostor);
  86299. //unregister events, if body is being changed
  86300. var oldBody = impostor.physicsBody;
  86301. if (oldBody) {
  86302. this.removePhysicsBody(impostor);
  86303. }
  86304. //create the body and material
  86305. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86306. var bodyCreationObject = {
  86307. mass: impostor.getParam("mass"),
  86308. material: material
  86309. };
  86310. // A simple extend, in case native options were used.
  86311. var nativeOptions = impostor.getParam("nativeOptions");
  86312. for (var key in nativeOptions) {
  86313. if (nativeOptions.hasOwnProperty(key)) {
  86314. bodyCreationObject[key] = nativeOptions[key];
  86315. }
  86316. }
  86317. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86318. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86319. this.world.addEventListener("preStep", impostor.beforeStep);
  86320. this.world.addEventListener("postStep", impostor.afterStep);
  86321. impostor.physicsBody.addShape(shape);
  86322. this.world.add(impostor.physicsBody);
  86323. //try to keep the body moving in the right direction by taking old properties.
  86324. //Should be tested!
  86325. if (oldBody) {
  86326. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86327. impostor.physicsBody[param].copy(oldBody[param]);
  86328. });
  86329. }
  86330. this._processChildMeshes(impostor);
  86331. }
  86332. //now update the body's transformation
  86333. this._updatePhysicsBodyTransformation(impostor);
  86334. };
  86335. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86336. var _this = this;
  86337. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86338. var currentRotation = mainImpostor.object.rotationQuaternion;
  86339. if (meshChildren.length) {
  86340. var processMesh = function (localPosition, mesh) {
  86341. if (!currentRotation || !mesh.rotationQuaternion) {
  86342. return;
  86343. }
  86344. var childImpostor = mesh.getPhysicsImpostor();
  86345. if (childImpostor) {
  86346. var parent = childImpostor.parent;
  86347. if (parent !== mainImpostor) {
  86348. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86349. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86350. if (childImpostor.physicsBody) {
  86351. _this.removePhysicsBody(childImpostor);
  86352. childImpostor.physicsBody = null;
  86353. }
  86354. childImpostor.parent = mainImpostor;
  86355. childImpostor.resetUpdateFlags();
  86356. 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));
  86357. //Add the mass of the children.
  86358. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86359. }
  86360. }
  86361. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86362. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86363. };
  86364. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86365. }
  86366. };
  86367. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86368. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86369. this.world.removeEventListener("preStep", impostor.beforeStep);
  86370. this.world.removeEventListener("postStep", impostor.afterStep);
  86371. this.world.remove(impostor.physicsBody);
  86372. };
  86373. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86374. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86375. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86376. if (!mainBody || !connectedBody) {
  86377. return;
  86378. }
  86379. var constraint;
  86380. var jointData = impostorJoint.joint.jointData;
  86381. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86382. var constraintData = {
  86383. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86384. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86385. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86386. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86387. maxForce: jointData.nativeParams.maxForce,
  86388. collideConnected: !!jointData.collision
  86389. };
  86390. switch (impostorJoint.joint.type) {
  86391. case BABYLON.PhysicsJoint.HingeJoint:
  86392. case BABYLON.PhysicsJoint.Hinge2Joint:
  86393. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86394. break;
  86395. case BABYLON.PhysicsJoint.DistanceJoint:
  86396. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86397. break;
  86398. case BABYLON.PhysicsJoint.SpringJoint:
  86399. var springData = jointData;
  86400. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86401. restLength: springData.length,
  86402. stiffness: springData.stiffness,
  86403. damping: springData.damping,
  86404. localAnchorA: constraintData.pivotA,
  86405. localAnchorB: constraintData.pivotB
  86406. });
  86407. break;
  86408. case BABYLON.PhysicsJoint.LockJoint:
  86409. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86410. break;
  86411. case BABYLON.PhysicsJoint.PointToPointJoint:
  86412. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86413. default:
  86414. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86415. break;
  86416. }
  86417. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86418. constraint.collideConnected = !!jointData.collision;
  86419. impostorJoint.joint.physicsJoint = constraint;
  86420. //don't add spring as constraint, as it is not one.
  86421. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86422. this.world.addConstraint(constraint);
  86423. }
  86424. else {
  86425. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86426. constraint.applyForce();
  86427. });
  86428. }
  86429. };
  86430. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86431. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86432. };
  86433. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86434. var index;
  86435. var mat;
  86436. for (index = 0; index < this._physicsMaterials.length; index++) {
  86437. mat = this._physicsMaterials[index];
  86438. if (mat.friction === friction && mat.restitution === restitution) {
  86439. return mat;
  86440. }
  86441. }
  86442. var currentMat = new this.BJSCANNON.Material(name);
  86443. currentMat.friction = friction;
  86444. currentMat.restitution = restitution;
  86445. this._physicsMaterials.push(currentMat);
  86446. return currentMat;
  86447. };
  86448. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86449. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86450. };
  86451. CannonJSPlugin.prototype._createShape = function (impostor) {
  86452. var object = impostor.object;
  86453. var returnValue;
  86454. var extendSize = impostor.getObjectExtendSize();
  86455. switch (impostor.type) {
  86456. case BABYLON.PhysicsImpostor.SphereImpostor:
  86457. var radiusX = extendSize.x;
  86458. var radiusY = extendSize.y;
  86459. var radiusZ = extendSize.z;
  86460. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86461. break;
  86462. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86463. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86464. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86465. break;
  86466. case BABYLON.PhysicsImpostor.BoxImpostor:
  86467. var box = extendSize.scale(0.5);
  86468. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86469. break;
  86470. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86471. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86472. returnValue = new this.BJSCANNON.Plane();
  86473. break;
  86474. case BABYLON.PhysicsImpostor.MeshImpostor:
  86475. // should transform the vertex data to world coordinates!!
  86476. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86477. var rawFaces = object.getIndices ? object.getIndices() : [];
  86478. if (!rawVerts)
  86479. return;
  86480. // get only scale! so the object could transform correctly.
  86481. var oldPosition = object.position.clone();
  86482. var oldRotation = object.rotation && object.rotation.clone();
  86483. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86484. object.position.copyFromFloats(0, 0, 0);
  86485. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86486. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86487. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86488. var transform = object.computeWorldMatrix(true);
  86489. // convert rawVerts to object space
  86490. var temp = new Array();
  86491. var index;
  86492. for (index = 0; index < rawVerts.length; index += 3) {
  86493. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86494. }
  86495. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86496. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86497. //now set back the transformation!
  86498. object.position.copyFrom(oldPosition);
  86499. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86500. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86501. break;
  86502. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86503. var oldPosition2 = object.position.clone();
  86504. var oldRotation2 = object.rotation && object.rotation.clone();
  86505. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86506. object.position.copyFromFloats(0, 0, 0);
  86507. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86508. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86509. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86510. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86511. returnValue = this._createHeightmap(object);
  86512. object.position.copyFrom(oldPosition2);
  86513. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86514. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86515. object.computeWorldMatrix(true);
  86516. break;
  86517. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86518. returnValue = new this.BJSCANNON.Particle();
  86519. break;
  86520. }
  86521. return returnValue;
  86522. };
  86523. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86524. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86525. var transform = object.computeWorldMatrix(true);
  86526. // convert rawVerts to object space
  86527. var temp = new Array();
  86528. var index;
  86529. for (index = 0; index < pos.length; index += 3) {
  86530. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86531. }
  86532. pos = temp;
  86533. var matrix = new Array();
  86534. //For now pointDepth will not be used and will be automatically calculated.
  86535. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86536. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86537. var boundingInfo = object.getBoundingInfo();
  86538. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86539. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86540. var elementSize = dim * 2 / arraySize;
  86541. for (var i = 0; i < pos.length; i = i + 3) {
  86542. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86543. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86544. var y = -pos[i + 2] + minY;
  86545. if (!matrix[x]) {
  86546. matrix[x] = [];
  86547. }
  86548. if (!matrix[x][z]) {
  86549. matrix[x][z] = y;
  86550. }
  86551. matrix[x][z] = Math.max(y, matrix[x][z]);
  86552. }
  86553. for (var x = 0; x <= arraySize; ++x) {
  86554. if (!matrix[x]) {
  86555. var loc = 1;
  86556. while (!matrix[(x + loc) % arraySize]) {
  86557. loc++;
  86558. }
  86559. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86560. //console.log("missing x", x);
  86561. }
  86562. for (var z = 0; z <= arraySize; ++z) {
  86563. if (!matrix[x][z]) {
  86564. var loc = 1;
  86565. var newValue;
  86566. while (newValue === undefined) {
  86567. newValue = matrix[x][(z + loc++) % arraySize];
  86568. }
  86569. matrix[x][z] = newValue;
  86570. }
  86571. }
  86572. }
  86573. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86574. elementSize: elementSize
  86575. });
  86576. //For future reference, needed for body transformation
  86577. shape.minY = minY;
  86578. return shape;
  86579. };
  86580. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86581. var object = impostor.object;
  86582. //make sure it is updated...
  86583. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86584. // The delta between the mesh position and the mesh bounding box center
  86585. var bInfo = object.getBoundingInfo();
  86586. if (!bInfo)
  86587. return;
  86588. var center = impostor.getObjectCenter();
  86589. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86590. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86591. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86592. this._tmpPosition.copyFrom(center);
  86593. var quaternion = object.rotationQuaternion;
  86594. if (!quaternion) {
  86595. return;
  86596. }
  86597. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86598. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86599. //-90 DEG in X, precalculated
  86600. quaternion = quaternion.multiply(this._minus90X);
  86601. //Invert! (Precalculated, 90 deg in X)
  86602. //No need to clone. this will never change.
  86603. impostor.setDeltaRotation(this._plus90X);
  86604. }
  86605. //If it is a heightfield, if should be centered.
  86606. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86607. var mesh = object;
  86608. var boundingInfo = mesh.getBoundingInfo();
  86609. //calculate the correct body position:
  86610. var rotationQuaternion = mesh.rotationQuaternion;
  86611. mesh.rotationQuaternion = this._tmpUnityRotation;
  86612. mesh.computeWorldMatrix(true);
  86613. //get original center with no rotation
  86614. var c = center.clone();
  86615. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86616. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86617. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86618. mesh.setPreTransformMatrix(p);
  86619. mesh.computeWorldMatrix(true);
  86620. //calculate the translation
  86621. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86622. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86623. //add it inverted to the delta
  86624. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86625. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86626. //rotation is back
  86627. mesh.rotationQuaternion = rotationQuaternion;
  86628. mesh.setPreTransformMatrix(oldPivot);
  86629. mesh.computeWorldMatrix(true);
  86630. }
  86631. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86632. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86633. //this._tmpPosition.copyFrom(object.position);
  86634. }
  86635. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86636. //Now update the impostor object
  86637. impostor.physicsBody.position.copy(this._tmpPosition);
  86638. impostor.physicsBody.quaternion.copy(quaternion);
  86639. };
  86640. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86641. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86642. if (impostor.object.rotationQuaternion) {
  86643. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86644. }
  86645. };
  86646. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86647. impostor.physicsBody.position.copy(newPosition);
  86648. impostor.physicsBody.quaternion.copy(newRotation);
  86649. };
  86650. CannonJSPlugin.prototype.isSupported = function () {
  86651. return this.BJSCANNON !== undefined;
  86652. };
  86653. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86654. impostor.physicsBody.velocity.copy(velocity);
  86655. };
  86656. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86657. impostor.physicsBody.angularVelocity.copy(velocity);
  86658. };
  86659. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86660. var v = impostor.physicsBody.velocity;
  86661. if (!v) {
  86662. return null;
  86663. }
  86664. return new BABYLON.Vector3(v.x, v.y, v.z);
  86665. };
  86666. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86667. var v = impostor.physicsBody.angularVelocity;
  86668. if (!v) {
  86669. return null;
  86670. }
  86671. return new BABYLON.Vector3(v.x, v.y, v.z);
  86672. };
  86673. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86674. impostor.physicsBody.mass = mass;
  86675. impostor.physicsBody.updateMassProperties();
  86676. };
  86677. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86678. return impostor.physicsBody.mass;
  86679. };
  86680. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86681. return impostor.physicsBody.material.friction;
  86682. };
  86683. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86684. impostor.physicsBody.material.friction = friction;
  86685. };
  86686. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86687. return impostor.physicsBody.material.restitution;
  86688. };
  86689. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86690. impostor.physicsBody.material.restitution = restitution;
  86691. };
  86692. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86693. impostor.physicsBody.sleep();
  86694. };
  86695. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86696. impostor.physicsBody.wakeUp();
  86697. };
  86698. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86699. joint.physicsJoint.distance = maxDistance;
  86700. };
  86701. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86702. // if (!motorIndex) {
  86703. // joint.physicsJoint.enableMotor();
  86704. // }
  86705. // }
  86706. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86707. // if (!motorIndex) {
  86708. // joint.physicsJoint.disableMotor();
  86709. // }
  86710. // }
  86711. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86712. if (!motorIndex) {
  86713. joint.physicsJoint.enableMotor();
  86714. joint.physicsJoint.setMotorSpeed(speed);
  86715. if (maxForce) {
  86716. this.setLimit(joint, maxForce);
  86717. }
  86718. }
  86719. };
  86720. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86721. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86722. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86723. };
  86724. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86725. var body = impostor.physicsBody;
  86726. mesh.position.x = body.position.x;
  86727. mesh.position.y = body.position.y;
  86728. mesh.position.z = body.position.z;
  86729. if (mesh.rotationQuaternion) {
  86730. mesh.rotationQuaternion.x = body.quaternion.x;
  86731. mesh.rotationQuaternion.y = body.quaternion.y;
  86732. mesh.rotationQuaternion.z = body.quaternion.z;
  86733. mesh.rotationQuaternion.w = body.quaternion.w;
  86734. }
  86735. };
  86736. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86737. var shape = impostor.physicsBody.shapes[0];
  86738. return shape.boundingSphereRadius;
  86739. };
  86740. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86741. var shape = impostor.physicsBody.shapes[0];
  86742. result.x = shape.halfExtents.x * 2;
  86743. result.y = shape.halfExtents.y * 2;
  86744. result.z = shape.halfExtents.z * 2;
  86745. };
  86746. CannonJSPlugin.prototype.dispose = function () {
  86747. };
  86748. CannonJSPlugin.prototype._extendNamespace = function () {
  86749. //this will force cannon to execute at least one step when using interpolation
  86750. var step_tmp1 = new this.BJSCANNON.Vec3();
  86751. var Engine = this.BJSCANNON;
  86752. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86753. maxSubSteps = maxSubSteps || 10;
  86754. timeSinceLastCalled = timeSinceLastCalled || 0;
  86755. if (timeSinceLastCalled === 0) {
  86756. this.internalStep(dt);
  86757. this.time += dt;
  86758. }
  86759. else {
  86760. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86761. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86762. var t0 = performance.now();
  86763. for (var i = 0; i !== internalSteps; i++) {
  86764. this.internalStep(dt);
  86765. if (performance.now() - t0 > dt * 1000) {
  86766. break;
  86767. }
  86768. }
  86769. this.time += timeSinceLastCalled;
  86770. var h = this.time % dt;
  86771. var h_div_dt = h / dt;
  86772. var interpvelo = step_tmp1;
  86773. var bodies = this.bodies;
  86774. for (var j = 0; j !== bodies.length; j++) {
  86775. var b = bodies[j];
  86776. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86777. b.position.vsub(b.previousPosition, interpvelo);
  86778. interpvelo.scale(h_div_dt, interpvelo);
  86779. b.position.vadd(interpvelo, b.interpolatedPosition);
  86780. }
  86781. else {
  86782. b.interpolatedPosition.copy(b.position);
  86783. b.interpolatedQuaternion.copy(b.quaternion);
  86784. }
  86785. }
  86786. }
  86787. };
  86788. };
  86789. return CannonJSPlugin;
  86790. }());
  86791. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86792. })(BABYLON || (BABYLON = {}));
  86793. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86794. var BABYLON;
  86795. (function (BABYLON) {
  86796. var OimoJSPlugin = /** @class */ (function () {
  86797. function OimoJSPlugin(iterations) {
  86798. this.name = "OimoJSPlugin";
  86799. this._tmpImpostorsArray = [];
  86800. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86801. this.BJSOIMO = OIMO;
  86802. this.world = new this.BJSOIMO.World({
  86803. iterations: iterations
  86804. });
  86805. this.world.clear();
  86806. }
  86807. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86808. this.world.gravity.copy(gravity);
  86809. };
  86810. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86811. this.world.timeStep = timeStep;
  86812. };
  86813. OimoJSPlugin.prototype.getTimeStep = function () {
  86814. return this.world.timeStep;
  86815. };
  86816. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86817. var _this = this;
  86818. impostors.forEach(function (impostor) {
  86819. impostor.beforeStep();
  86820. });
  86821. this.world.step();
  86822. impostors.forEach(function (impostor) {
  86823. impostor.afterStep();
  86824. //update the ordered impostors array
  86825. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86826. });
  86827. //check for collisions
  86828. var contact = this.world.contacts;
  86829. while (contact !== null) {
  86830. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86831. contact = contact.next;
  86832. continue;
  86833. }
  86834. //is this body colliding with any other? get the impostor
  86835. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86836. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86837. if (!mainImpostor || !collidingImpostor) {
  86838. contact = contact.next;
  86839. continue;
  86840. }
  86841. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86842. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86843. contact = contact.next;
  86844. }
  86845. };
  86846. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86847. var mass = impostor.physicsBody.mass;
  86848. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86849. };
  86850. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86851. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86852. this.applyImpulse(impostor, force, contactPoint);
  86853. };
  86854. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86855. var _this = this;
  86856. //parent-child relationship. Does this impostor has a parent impostor?
  86857. if (impostor.parent) {
  86858. if (impostor.physicsBody) {
  86859. this.removePhysicsBody(impostor);
  86860. //TODO is that needed?
  86861. impostor.forceUpdate();
  86862. }
  86863. return;
  86864. }
  86865. if (impostor.isBodyInitRequired()) {
  86866. var bodyConfig = {
  86867. name: impostor.uniqueId,
  86868. //Oimo must have mass, also for static objects.
  86869. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86870. size: [],
  86871. type: [],
  86872. pos: [],
  86873. posShape: [],
  86874. rot: [],
  86875. rotShape: [],
  86876. move: impostor.getParam("mass") !== 0,
  86877. density: impostor.getParam("mass"),
  86878. friction: impostor.getParam("friction"),
  86879. restitution: impostor.getParam("restitution"),
  86880. //Supporting older versions of Oimo
  86881. world: this.world
  86882. };
  86883. var impostors = [impostor];
  86884. var addToArray = function (parent) {
  86885. if (!parent.getChildMeshes)
  86886. return;
  86887. parent.getChildMeshes().forEach(function (m) {
  86888. if (m.physicsImpostor) {
  86889. impostors.push(m.physicsImpostor);
  86890. //m.physicsImpostor._init();
  86891. }
  86892. });
  86893. };
  86894. addToArray(impostor.object);
  86895. var checkWithEpsilon_1 = function (value) {
  86896. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86897. };
  86898. var globalQuaternion_1 = new BABYLON.Quaternion();
  86899. impostors.forEach(function (i) {
  86900. if (!i.object.rotationQuaternion) {
  86901. return;
  86902. }
  86903. //get the correct bounding box
  86904. var oldQuaternion = i.object.rotationQuaternion;
  86905. globalQuaternion_1 = oldQuaternion.clone();
  86906. var rot = oldQuaternion.toEulerAngles();
  86907. var extendSize = i.getObjectExtendSize();
  86908. var radToDeg = 57.295779513082320876;
  86909. if (i === impostor) {
  86910. var center = impostor.getObjectCenter();
  86911. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86912. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86913. //Can also use Array.prototype.push.apply
  86914. bodyConfig.pos.push(center.x);
  86915. bodyConfig.pos.push(center.y);
  86916. bodyConfig.pos.push(center.z);
  86917. bodyConfig.posShape.push(0, 0, 0);
  86918. //tmp solution
  86919. bodyConfig.rot.push(0);
  86920. bodyConfig.rot.push(0);
  86921. bodyConfig.rot.push(0);
  86922. bodyConfig.rotShape.push(0, 0, 0);
  86923. }
  86924. else {
  86925. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86926. bodyConfig.posShape.push(localPosition.x);
  86927. bodyConfig.posShape.push(localPosition.y);
  86928. bodyConfig.posShape.push(localPosition.z);
  86929. bodyConfig.pos.push(0, 0, 0);
  86930. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86931. bodyConfig.rot.push(0);
  86932. bodyConfig.rot.push(0);
  86933. bodyConfig.rot.push(0);
  86934. bodyConfig.rotShape.push(rot.x * radToDeg);
  86935. bodyConfig.rotShape.push(rot.y * radToDeg);
  86936. bodyConfig.rotShape.push(rot.z * radToDeg);
  86937. }
  86938. // register mesh
  86939. switch (i.type) {
  86940. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86941. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86942. case BABYLON.PhysicsImpostor.SphereImpostor:
  86943. var radiusX = extendSize.x;
  86944. var radiusY = extendSize.y;
  86945. var radiusZ = extendSize.z;
  86946. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86947. bodyConfig.type.push('sphere');
  86948. //due to the way oimo works with compounds, add 3 times
  86949. bodyConfig.size.push(size);
  86950. bodyConfig.size.push(size);
  86951. bodyConfig.size.push(size);
  86952. break;
  86953. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86954. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86955. var sizeY = checkWithEpsilon_1(extendSize.y);
  86956. bodyConfig.type.push('cylinder');
  86957. bodyConfig.size.push(sizeX);
  86958. bodyConfig.size.push(sizeY);
  86959. //due to the way oimo works with compounds, add one more value.
  86960. bodyConfig.size.push(sizeY);
  86961. break;
  86962. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86963. case BABYLON.PhysicsImpostor.BoxImpostor:
  86964. default:
  86965. var sizeX = checkWithEpsilon_1(extendSize.x);
  86966. var sizeY = checkWithEpsilon_1(extendSize.y);
  86967. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86968. bodyConfig.type.push('box');
  86969. //if (i === impostor) {
  86970. bodyConfig.size.push(sizeX);
  86971. bodyConfig.size.push(sizeY);
  86972. bodyConfig.size.push(sizeZ);
  86973. //} else {
  86974. // bodyConfig.size.push(0,0,0);
  86975. //}
  86976. break;
  86977. }
  86978. //actually not needed, but hey...
  86979. i.object.rotationQuaternion = oldQuaternion;
  86980. });
  86981. impostor.physicsBody = this.world.add(bodyConfig);
  86982. // set the quaternion, ignoring the previously defined (euler) rotation
  86983. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  86984. // update with delta 0, so the body will reveive the new rotation.
  86985. impostor.physicsBody.updatePosition(0);
  86986. }
  86987. else {
  86988. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86989. }
  86990. impostor.setDeltaPosition(this._tmpPositionVector);
  86991. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86992. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86993. };
  86994. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86995. //impostor.physicsBody.dispose();
  86996. //Same as : (older oimo versions)
  86997. this.world.removeRigidBody(impostor.physicsBody);
  86998. };
  86999. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  87000. var mainBody = impostorJoint.mainImpostor.physicsBody;
  87001. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  87002. if (!mainBody || !connectedBody) {
  87003. return;
  87004. }
  87005. var jointData = impostorJoint.joint.jointData;
  87006. var options = jointData.nativeParams || {};
  87007. var type;
  87008. var nativeJointData = {
  87009. body1: mainBody,
  87010. body2: connectedBody,
  87011. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  87012. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  87013. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  87014. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  87015. min: options.min,
  87016. max: options.max,
  87017. collision: options.collision || jointData.collision,
  87018. spring: options.spring,
  87019. //supporting older version of Oimo
  87020. world: this.world
  87021. };
  87022. switch (impostorJoint.joint.type) {
  87023. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87024. type = "jointBall";
  87025. break;
  87026. case BABYLON.PhysicsJoint.SpringJoint:
  87027. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  87028. var springData = jointData;
  87029. nativeJointData.min = springData.length || nativeJointData.min;
  87030. //Max should also be set, just make sure it is at least min
  87031. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  87032. case BABYLON.PhysicsJoint.DistanceJoint:
  87033. type = "jointDistance";
  87034. nativeJointData.max = jointData.maxDistance;
  87035. break;
  87036. case BABYLON.PhysicsJoint.PrismaticJoint:
  87037. type = "jointPrisme";
  87038. break;
  87039. case BABYLON.PhysicsJoint.SliderJoint:
  87040. type = "jointSlide";
  87041. break;
  87042. case BABYLON.PhysicsJoint.WheelJoint:
  87043. type = "jointWheel";
  87044. break;
  87045. case BABYLON.PhysicsJoint.HingeJoint:
  87046. default:
  87047. type = "jointHinge";
  87048. break;
  87049. }
  87050. nativeJointData.type = type;
  87051. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  87052. };
  87053. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87054. //Bug in Oimo prevents us from disposing a joint in the playground
  87055. //joint.joint.physicsJoint.dispose();
  87056. //So we will bruteforce it!
  87057. try {
  87058. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  87059. }
  87060. catch (e) {
  87061. BABYLON.Tools.Warn(e);
  87062. }
  87063. };
  87064. OimoJSPlugin.prototype.isSupported = function () {
  87065. return this.BJSOIMO !== undefined;
  87066. };
  87067. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87068. if (!impostor.physicsBody.sleeping) {
  87069. //TODO check that
  87070. /*if (impostor.physicsBody.shapes.next) {
  87071. var parentShape = this._getLastShape(impostor.physicsBody);
  87072. impostor.object.position.copyFrom(parentShape.position);
  87073. console.log(parentShape.position);
  87074. } else {*/
  87075. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  87076. //}
  87077. if (impostor.object.rotationQuaternion) {
  87078. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  87079. }
  87080. }
  87081. };
  87082. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87083. var body = impostor.physicsBody;
  87084. body.position.copy(newPosition);
  87085. body.orientation.copy(newRotation);
  87086. body.syncShapes();
  87087. body.awake();
  87088. };
  87089. /*private _getLastShape(body: any): any {
  87090. var lastShape = body.shapes;
  87091. while (lastShape.next) {
  87092. lastShape = lastShape.next;
  87093. }
  87094. return lastShape;
  87095. }*/
  87096. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87097. impostor.physicsBody.linearVelocity.copy(velocity);
  87098. };
  87099. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87100. impostor.physicsBody.angularVelocity.copy(velocity);
  87101. };
  87102. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87103. var v = impostor.physicsBody.linearVelocity;
  87104. if (!v) {
  87105. return null;
  87106. }
  87107. return new BABYLON.Vector3(v.x, v.y, v.z);
  87108. };
  87109. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87110. var v = impostor.physicsBody.angularVelocity;
  87111. if (!v) {
  87112. return null;
  87113. }
  87114. return new BABYLON.Vector3(v.x, v.y, v.z);
  87115. };
  87116. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87117. var staticBody = mass === 0;
  87118. //this will actually set the body's density and not its mass.
  87119. //But this is how oimo treats the mass variable.
  87120. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  87121. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  87122. };
  87123. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  87124. return impostor.physicsBody.shapes.density;
  87125. };
  87126. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  87127. return impostor.physicsBody.shapes.friction;
  87128. };
  87129. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87130. impostor.physicsBody.shapes.friction = friction;
  87131. };
  87132. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87133. return impostor.physicsBody.shapes.restitution;
  87134. };
  87135. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87136. impostor.physicsBody.shapes.restitution = restitution;
  87137. };
  87138. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  87139. impostor.physicsBody.sleep();
  87140. };
  87141. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  87142. impostor.physicsBody.awake();
  87143. };
  87144. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87145. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  87146. if (minDistance !== void 0) {
  87147. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  87148. }
  87149. };
  87150. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87151. //TODO separate rotational and transational motors.
  87152. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87153. if (motor) {
  87154. motor.setMotor(speed, maxForce);
  87155. }
  87156. };
  87157. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  87158. //TODO separate rotational and transational motors.
  87159. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87160. if (motor) {
  87161. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  87162. }
  87163. };
  87164. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87165. var body = impostor.physicsBody;
  87166. mesh.position.x = body.position.x;
  87167. mesh.position.y = body.position.y;
  87168. mesh.position.z = body.position.z;
  87169. if (mesh.rotationQuaternion) {
  87170. mesh.rotationQuaternion.x = body.orientation.x;
  87171. mesh.rotationQuaternion.y = body.orientation.y;
  87172. mesh.rotationQuaternion.z = body.orientation.z;
  87173. mesh.rotationQuaternion.w = body.orientation.s;
  87174. }
  87175. };
  87176. OimoJSPlugin.prototype.getRadius = function (impostor) {
  87177. return impostor.physicsBody.shapes.radius;
  87178. };
  87179. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87180. var shape = impostor.physicsBody.shapes;
  87181. result.x = shape.halfWidth * 2;
  87182. result.y = shape.halfHeight * 2;
  87183. result.z = shape.halfDepth * 2;
  87184. };
  87185. OimoJSPlugin.prototype.dispose = function () {
  87186. this.world.clear();
  87187. };
  87188. return OimoJSPlugin;
  87189. }());
  87190. BABYLON.OimoJSPlugin = OimoJSPlugin;
  87191. })(BABYLON || (BABYLON = {}));
  87192. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  87193. var BABYLON;
  87194. (function (BABYLON) {
  87195. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87196. // All values and structures referenced from:
  87197. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87198. var DDS_MAGIC = 0x20534444;
  87199. var
  87200. //DDSD_CAPS = 0x1,
  87201. //DDSD_HEIGHT = 0x2,
  87202. //DDSD_WIDTH = 0x4,
  87203. //DDSD_PITCH = 0x8,
  87204. //DDSD_PIXELFORMAT = 0x1000,
  87205. DDSD_MIPMAPCOUNT = 0x20000;
  87206. //DDSD_LINEARSIZE = 0x80000,
  87207. //DDSD_DEPTH = 0x800000;
  87208. // var DDSCAPS_COMPLEX = 0x8,
  87209. // DDSCAPS_MIPMAP = 0x400000,
  87210. // DDSCAPS_TEXTURE = 0x1000;
  87211. var DDSCAPS2_CUBEMAP = 0x200;
  87212. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87213. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87214. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87215. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87216. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87217. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87218. // DDSCAPS2_VOLUME = 0x200000;
  87219. var
  87220. //DDPF_ALPHAPIXELS = 0x1,
  87221. //DDPF_ALPHA = 0x2,
  87222. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87223. //DDPF_YUV = 0x200,
  87224. DDPF_LUMINANCE = 0x20000;
  87225. function FourCCToInt32(value) {
  87226. return value.charCodeAt(0) +
  87227. (value.charCodeAt(1) << 8) +
  87228. (value.charCodeAt(2) << 16) +
  87229. (value.charCodeAt(3) << 24);
  87230. }
  87231. function Int32ToFourCC(value) {
  87232. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87233. }
  87234. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87235. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87236. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87237. var FOURCC_DX10 = FourCCToInt32("DX10");
  87238. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87239. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87240. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87241. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87242. var headerLengthInt = 31; // The header length in 32 bit ints
  87243. // Offsets into the header array
  87244. var off_magic = 0;
  87245. var off_size = 1;
  87246. var off_flags = 2;
  87247. var off_height = 3;
  87248. var off_width = 4;
  87249. var off_mipmapCount = 7;
  87250. var off_pfFlags = 20;
  87251. var off_pfFourCC = 21;
  87252. var off_RGBbpp = 22;
  87253. var off_RMask = 23;
  87254. var off_GMask = 24;
  87255. var off_BMask = 25;
  87256. var off_AMask = 26;
  87257. // var off_caps1 = 27;
  87258. var off_caps2 = 28;
  87259. // var off_caps3 = 29;
  87260. // var off_caps4 = 30;
  87261. var off_dxgiFormat = 32;
  87262. ;
  87263. var DDSTools = /** @class */ (function () {
  87264. function DDSTools() {
  87265. }
  87266. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87267. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87268. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87269. var mipmapCount = 1;
  87270. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87271. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87272. }
  87273. var fourCC = header[off_pfFourCC];
  87274. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87275. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87276. switch (fourCC) {
  87277. case FOURCC_D3DFMT_R16G16B16A16F:
  87278. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87279. break;
  87280. case FOURCC_D3DFMT_R32G32B32A32F:
  87281. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87282. break;
  87283. case FOURCC_DX10:
  87284. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87285. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87286. break;
  87287. }
  87288. }
  87289. return {
  87290. width: header[off_width],
  87291. height: header[off_height],
  87292. mipmapCount: mipmapCount,
  87293. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87294. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87295. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87296. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87297. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87298. dxgiFormat: dxgiFormat,
  87299. textureType: textureType
  87300. };
  87301. };
  87302. DDSTools._ToHalfFloat = function (value) {
  87303. if (!DDSTools._FloatView) {
  87304. DDSTools._FloatView = new Float32Array(1);
  87305. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87306. }
  87307. DDSTools._FloatView[0] = value;
  87308. var x = DDSTools._Int32View[0];
  87309. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87310. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87311. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87312. /* If zero, or denormal, or exponent underflows too much for a denormal
  87313. * half, return signed zero. */
  87314. if (e < 103) {
  87315. return bits;
  87316. }
  87317. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87318. if (e > 142) {
  87319. bits |= 0x7c00;
  87320. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87321. * not Inf, so make sure we set one mantissa bit too. */
  87322. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87323. return bits;
  87324. }
  87325. /* If exponent underflows but not too much, return a denormal */
  87326. if (e < 113) {
  87327. m |= 0x0800;
  87328. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87329. * to 1, which is OK. */
  87330. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87331. return bits;
  87332. }
  87333. bits |= ((e - 112) << 10) | (m >> 1);
  87334. bits += m & 1;
  87335. return bits;
  87336. };
  87337. DDSTools._FromHalfFloat = function (value) {
  87338. var s = (value & 0x8000) >> 15;
  87339. var e = (value & 0x7C00) >> 10;
  87340. var f = value & 0x03FF;
  87341. if (e === 0) {
  87342. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87343. }
  87344. else if (e == 0x1F) {
  87345. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87346. }
  87347. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87348. };
  87349. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87350. var destArray = new Float32Array(dataLength);
  87351. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87352. var index = 0;
  87353. for (var y = 0; y < height; y++) {
  87354. for (var x = 0; x < width; x++) {
  87355. var srcPos = (x + y * width) * 4;
  87356. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87357. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87358. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87359. if (DDSTools.StoreLODInAlphaChannel) {
  87360. destArray[index + 3] = lod;
  87361. }
  87362. else {
  87363. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87364. }
  87365. index += 4;
  87366. }
  87367. }
  87368. return destArray;
  87369. };
  87370. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87371. if (DDSTools.StoreLODInAlphaChannel) {
  87372. var destArray = new Uint16Array(dataLength);
  87373. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87374. var index = 0;
  87375. for (var y = 0; y < height; y++) {
  87376. for (var x = 0; x < width; x++) {
  87377. var srcPos = (x + y * width) * 4;
  87378. destArray[index] = srcData[srcPos];
  87379. destArray[index + 1] = srcData[srcPos + 1];
  87380. destArray[index + 2] = srcData[srcPos + 2];
  87381. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87382. index += 4;
  87383. }
  87384. }
  87385. return destArray;
  87386. }
  87387. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87388. };
  87389. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87390. if (DDSTools.StoreLODInAlphaChannel) {
  87391. var destArray = new Float32Array(dataLength);
  87392. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87393. var index = 0;
  87394. for (var y = 0; y < height; y++) {
  87395. for (var x = 0; x < width; x++) {
  87396. var srcPos = (x + y * width) * 4;
  87397. destArray[index] = srcData[srcPos];
  87398. destArray[index + 1] = srcData[srcPos + 1];
  87399. destArray[index + 2] = srcData[srcPos + 2];
  87400. destArray[index + 3] = lod;
  87401. index += 4;
  87402. }
  87403. }
  87404. return destArray;
  87405. }
  87406. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87407. };
  87408. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87409. var destArray = new Uint8Array(dataLength);
  87410. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87411. var index = 0;
  87412. for (var y = 0; y < height; y++) {
  87413. for (var x = 0; x < width; x++) {
  87414. var srcPos = (x + y * width) * 4;
  87415. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87416. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87417. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87418. if (DDSTools.StoreLODInAlphaChannel) {
  87419. destArray[index + 3] = lod;
  87420. }
  87421. else {
  87422. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87423. }
  87424. index += 4;
  87425. }
  87426. }
  87427. return destArray;
  87428. };
  87429. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87430. var destArray = new Uint8Array(dataLength);
  87431. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87432. var index = 0;
  87433. for (var y = 0; y < height; y++) {
  87434. for (var x = 0; x < width; x++) {
  87435. var srcPos = (x + y * width) * 4;
  87436. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87437. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87438. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87439. if (DDSTools.StoreLODInAlphaChannel) {
  87440. destArray[index + 3] = lod;
  87441. }
  87442. else {
  87443. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87444. }
  87445. index += 4;
  87446. }
  87447. }
  87448. return destArray;
  87449. };
  87450. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87451. var byteArray = new Uint8Array(dataLength);
  87452. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87453. var index = 0;
  87454. for (var y = 0; y < height; y++) {
  87455. for (var x = 0; x < width; x++) {
  87456. var srcPos = (x + y * width) * 4;
  87457. byteArray[index] = srcData[srcPos + rOffset];
  87458. byteArray[index + 1] = srcData[srcPos + gOffset];
  87459. byteArray[index + 2] = srcData[srcPos + bOffset];
  87460. byteArray[index + 3] = srcData[srcPos + aOffset];
  87461. index += 4;
  87462. }
  87463. }
  87464. return byteArray;
  87465. };
  87466. DDSTools._ExtractLongWordOrder = function (value) {
  87467. if (value === 0 || value === 255 || value === -16777216) {
  87468. return 0;
  87469. }
  87470. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87471. };
  87472. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87473. var byteArray = new Uint8Array(dataLength);
  87474. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87475. var index = 0;
  87476. for (var y = 0; y < height; y++) {
  87477. for (var x = 0; x < width; x++) {
  87478. var srcPos = (x + y * width) * 3;
  87479. byteArray[index] = srcData[srcPos + rOffset];
  87480. byteArray[index + 1] = srcData[srcPos + gOffset];
  87481. byteArray[index + 2] = srcData[srcPos + bOffset];
  87482. index += 3;
  87483. }
  87484. }
  87485. return byteArray;
  87486. };
  87487. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87488. var byteArray = new Uint8Array(dataLength);
  87489. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87490. var index = 0;
  87491. for (var y = 0; y < height; y++) {
  87492. for (var x = 0; x < width; x++) {
  87493. var srcPos = (x + y * width);
  87494. byteArray[index] = srcData[srcPos];
  87495. index++;
  87496. }
  87497. }
  87498. return byteArray;
  87499. };
  87500. /**
  87501. * Uploads DDS Levels to a Babylon Texture
  87502. * @hidden
  87503. */
  87504. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87505. if (lodIndex === void 0) { lodIndex = -1; }
  87506. var sphericalPolynomialFaces = null;
  87507. if (info.sphericalPolynomial) {
  87508. sphericalPolynomialFaces = new Array();
  87509. }
  87510. var ext = engine.getCaps().s3tc;
  87511. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87512. var fourCC, width, height, dataLength = 0, dataOffset;
  87513. var byteArray, mipmapCount, mip;
  87514. var internalCompressedFormat = 0;
  87515. var blockBytes = 1;
  87516. if (header[off_magic] !== DDS_MAGIC) {
  87517. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87518. return;
  87519. }
  87520. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87521. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87522. return;
  87523. }
  87524. if (info.isCompressed && !ext) {
  87525. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87526. return;
  87527. }
  87528. var bpp = header[off_RGBbpp];
  87529. dataOffset = header[off_size] + 4;
  87530. var computeFormats = false;
  87531. if (info.isFourCC) {
  87532. fourCC = header[off_pfFourCC];
  87533. switch (fourCC) {
  87534. case FOURCC_DXT1:
  87535. blockBytes = 8;
  87536. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87537. break;
  87538. case FOURCC_DXT3:
  87539. blockBytes = 16;
  87540. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87541. break;
  87542. case FOURCC_DXT5:
  87543. blockBytes = 16;
  87544. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87545. break;
  87546. case FOURCC_D3DFMT_R16G16B16A16F:
  87547. computeFormats = true;
  87548. break;
  87549. case FOURCC_D3DFMT_R32G32B32A32F:
  87550. computeFormats = true;
  87551. break;
  87552. case FOURCC_DX10:
  87553. // There is an additionnal header so dataOffset need to be changed
  87554. dataOffset += 5 * 4; // 5 uints
  87555. var supported = false;
  87556. switch (info.dxgiFormat) {
  87557. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87558. computeFormats = true;
  87559. supported = true;
  87560. break;
  87561. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87562. info.isRGB = true;
  87563. info.isFourCC = false;
  87564. bpp = 32;
  87565. supported = true;
  87566. break;
  87567. }
  87568. if (supported) {
  87569. break;
  87570. }
  87571. default:
  87572. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87573. return;
  87574. }
  87575. }
  87576. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87577. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87578. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87579. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87580. if (computeFormats) {
  87581. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87582. }
  87583. mipmapCount = 1;
  87584. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87585. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87586. }
  87587. for (var face = 0; face < faces; face++) {
  87588. width = header[off_width];
  87589. height = header[off_height];
  87590. for (mip = 0; mip < mipmapCount; ++mip) {
  87591. if (lodIndex === -1 || lodIndex === mip) {
  87592. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87593. var i = (lodIndex === -1) ? mip : 0;
  87594. if (!info.isCompressed && info.isFourCC) {
  87595. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87596. dataLength = width * height * 4;
  87597. var floatArray = null;
  87598. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87599. if (bpp === 128) {
  87600. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87601. if (sphericalPolynomialFaces && i == 0) {
  87602. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87603. }
  87604. }
  87605. else if (bpp === 64) {
  87606. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87607. if (sphericalPolynomialFaces && i == 0) {
  87608. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87609. }
  87610. }
  87611. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87612. }
  87613. else {
  87614. if (bpp === 128) {
  87615. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87616. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87617. if (sphericalPolynomialFaces && i == 0) {
  87618. sphericalPolynomialFaces.push(floatArray);
  87619. }
  87620. }
  87621. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87622. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87623. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87624. if (sphericalPolynomialFaces && i == 0) {
  87625. sphericalPolynomialFaces.push(floatArray);
  87626. }
  87627. }
  87628. else { // 64
  87629. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87630. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87631. if (sphericalPolynomialFaces && i == 0) {
  87632. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87633. }
  87634. }
  87635. }
  87636. if (floatArray) {
  87637. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  87638. }
  87639. }
  87640. else if (info.isRGB) {
  87641. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87642. if (bpp === 24) {
  87643. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  87644. dataLength = width * height * 3;
  87645. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87646. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87647. }
  87648. else { // 32
  87649. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87650. dataLength = width * height * 4;
  87651. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87652. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87653. }
  87654. }
  87655. else if (info.isLuminance) {
  87656. var unpackAlignment = engine._getUnpackAlignement();
  87657. var unpaddedRowSize = width;
  87658. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87659. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87660. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87661. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  87662. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87663. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87664. }
  87665. else {
  87666. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87667. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87668. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87669. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  87670. }
  87671. }
  87672. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87673. width *= 0.5;
  87674. height *= 0.5;
  87675. width = Math.max(1.0, width);
  87676. height = Math.max(1.0, height);
  87677. }
  87678. if (currentFace !== undefined) {
  87679. // Loading a single face
  87680. break;
  87681. }
  87682. }
  87683. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87684. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87685. size: header[off_width],
  87686. right: sphericalPolynomialFaces[0],
  87687. left: sphericalPolynomialFaces[1],
  87688. up: sphericalPolynomialFaces[2],
  87689. down: sphericalPolynomialFaces[3],
  87690. front: sphericalPolynomialFaces[4],
  87691. back: sphericalPolynomialFaces[5],
  87692. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87693. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87694. gammaSpace: false,
  87695. });
  87696. }
  87697. else {
  87698. info.sphericalPolynomial = undefined;
  87699. }
  87700. };
  87701. DDSTools.StoreLODInAlphaChannel = false;
  87702. return DDSTools;
  87703. }());
  87704. BABYLON.DDSTools = DDSTools;
  87705. })(BABYLON || (BABYLON = {}));
  87706. //# sourceMappingURL=babylon.dds.js.map
  87707. var BABYLON;
  87708. (function (BABYLON) {
  87709. /**
  87710. * Implementation of the DDS Texture Loader.
  87711. */
  87712. var DDSTextureLoader = /** @class */ (function () {
  87713. function DDSTextureLoader() {
  87714. /**
  87715. * Defines wether the loader supports cascade loading the different faces.
  87716. */
  87717. this.supportCascades = true;
  87718. }
  87719. /**
  87720. * This returns if the loader support the current file information.
  87721. * @param extension defines the file extension of the file being loaded
  87722. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87723. * @param fallback defines the fallback internal texture if any
  87724. * @param isBase64 defines whether the texture is encoded as a base64
  87725. * @param isBuffer defines whether the texture data are stored as a buffer
  87726. * @returns true if the loader can load the specified file
  87727. */
  87728. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  87729. return extension.indexOf(".dds") === 0;
  87730. };
  87731. /**
  87732. * Transform the url before loading if required.
  87733. * @param rootUrl the url of the texture
  87734. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87735. * @returns the transformed texture
  87736. */
  87737. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  87738. return rootUrl;
  87739. };
  87740. /**
  87741. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  87742. * @param rootUrl the url of the texture
  87743. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87744. * @returns the fallback texture
  87745. */
  87746. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  87747. return null;
  87748. };
  87749. /**
  87750. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  87751. * @param data contains the texture data
  87752. * @param texture defines the BabylonJS internal texture
  87753. * @param createPolynomials will be true if polynomials have been requested
  87754. * @param onLoad defines the callback to trigger once the texture is ready
  87755. * @param onError defines the callback to trigger in case of error
  87756. */
  87757. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  87758. var engine = texture.getEngine();
  87759. var info;
  87760. var loadMipmap = false;
  87761. if (Array.isArray(imgs)) {
  87762. for (var index = 0; index < imgs.length; index++) {
  87763. var data_1 = imgs[index];
  87764. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  87765. texture.width = info.width;
  87766. texture.height = info.height;
  87767. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  87768. engine._unpackFlipY(info.isCompressed);
  87769. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  87770. if (!info.isFourCC && info.mipmapCount === 1) {
  87771. engine.generateMipMapsForCubemap(texture);
  87772. }
  87773. }
  87774. }
  87775. else {
  87776. var data = imgs;
  87777. info = BABYLON.DDSTools.GetDDSInfo(data);
  87778. texture.width = info.width;
  87779. texture.height = info.height;
  87780. if (createPolynomials) {
  87781. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  87782. }
  87783. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  87784. engine._unpackFlipY(info.isCompressed);
  87785. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  87786. if (!info.isFourCC && info.mipmapCount === 1) {
  87787. engine.generateMipMapsForCubemap(texture);
  87788. }
  87789. }
  87790. engine._setCubeMapTextureParams(loadMipmap);
  87791. texture.isReady = true;
  87792. if (onLoad) {
  87793. onLoad({ isDDS: true, width: texture.width, info: info, imgs: imgs, texture: texture });
  87794. }
  87795. };
  87796. /**
  87797. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  87798. * @param data contains the texture data
  87799. * @param texture defines the BabylonJS internal texture
  87800. * @param callback defines the method to call once ready to upload
  87801. */
  87802. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  87803. var info = BABYLON.DDSTools.GetDDSInfo(data);
  87804. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  87805. callback(info.width, info.height, !loadMipmap, info.isFourCC, function () {
  87806. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  87807. });
  87808. };
  87809. return DDSTextureLoader;
  87810. }());
  87811. // Register the loader.
  87812. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  87813. })(BABYLON || (BABYLON = {}));
  87814. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  87815. var BABYLON;
  87816. (function (BABYLON) {
  87817. /*
  87818. * Based on jsTGALoader - Javascript loader for TGA file
  87819. * By Vincent Thibault
  87820. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  87821. */
  87822. var TGATools = /** @class */ (function () {
  87823. function TGATools() {
  87824. }
  87825. TGATools.GetTGAHeader = function (data) {
  87826. var offset = 0;
  87827. var header = {
  87828. id_length: data[offset++],
  87829. colormap_type: data[offset++],
  87830. image_type: data[offset++],
  87831. colormap_index: data[offset++] | data[offset++] << 8,
  87832. colormap_length: data[offset++] | data[offset++] << 8,
  87833. colormap_size: data[offset++],
  87834. origin: [
  87835. data[offset++] | data[offset++] << 8,
  87836. data[offset++] | data[offset++] << 8
  87837. ],
  87838. width: data[offset++] | data[offset++] << 8,
  87839. height: data[offset++] | data[offset++] << 8,
  87840. pixel_size: data[offset++],
  87841. flags: data[offset++]
  87842. };
  87843. return header;
  87844. };
  87845. /**
  87846. * Uploads TGA content to a Babylon Texture
  87847. * @hidden
  87848. */
  87849. TGATools.UploadContent = function (texture, data) {
  87850. // Not enough data to contain header ?
  87851. if (data.length < 19) {
  87852. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  87853. return;
  87854. }
  87855. // Read Header
  87856. var offset = 18;
  87857. var header = TGATools.GetTGAHeader(data);
  87858. // Assume it's a valid Targa file.
  87859. if (header.id_length + offset > data.length) {
  87860. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  87861. return;
  87862. }
  87863. // Skip not needed data
  87864. offset += header.id_length;
  87865. var use_rle = false;
  87866. var use_pal = false;
  87867. var use_grey = false;
  87868. // Get some informations.
  87869. switch (header.image_type) {
  87870. case TGATools._TYPE_RLE_INDEXED:
  87871. use_rle = true;
  87872. case TGATools._TYPE_INDEXED:
  87873. use_pal = true;
  87874. break;
  87875. case TGATools._TYPE_RLE_RGB:
  87876. use_rle = true;
  87877. case TGATools._TYPE_RGB:
  87878. // use_rgb = true;
  87879. break;
  87880. case TGATools._TYPE_RLE_GREY:
  87881. use_rle = true;
  87882. case TGATools._TYPE_GREY:
  87883. use_grey = true;
  87884. break;
  87885. }
  87886. var pixel_data;
  87887. // var numAlphaBits = header.flags & 0xf;
  87888. var pixel_size = header.pixel_size >> 3;
  87889. var pixel_total = header.width * header.height * pixel_size;
  87890. // Read palettes
  87891. var palettes;
  87892. if (use_pal) {
  87893. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  87894. }
  87895. // Read LRE
  87896. if (use_rle) {
  87897. pixel_data = new Uint8Array(pixel_total);
  87898. var c, count, i;
  87899. var localOffset = 0;
  87900. var pixels = new Uint8Array(pixel_size);
  87901. while (offset < pixel_total && localOffset < pixel_total) {
  87902. c = data[offset++];
  87903. count = (c & 0x7f) + 1;
  87904. // RLE pixels
  87905. if (c & 0x80) {
  87906. // Bind pixel tmp array
  87907. for (i = 0; i < pixel_size; ++i) {
  87908. pixels[i] = data[offset++];
  87909. }
  87910. // Copy pixel array
  87911. for (i = 0; i < count; ++i) {
  87912. pixel_data.set(pixels, localOffset + i * pixel_size);
  87913. }
  87914. localOffset += pixel_size * count;
  87915. }
  87916. // Raw pixels
  87917. else {
  87918. count *= pixel_size;
  87919. for (i = 0; i < count; ++i) {
  87920. pixel_data[localOffset + i] = data[offset++];
  87921. }
  87922. localOffset += count;
  87923. }
  87924. }
  87925. }
  87926. // RAW Pixels
  87927. else {
  87928. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  87929. }
  87930. // Load to texture
  87931. var x_start, y_start, x_step, y_step, y_end, x_end;
  87932. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  87933. default:
  87934. case TGATools._ORIGIN_UL:
  87935. x_start = 0;
  87936. x_step = 1;
  87937. x_end = header.width;
  87938. y_start = 0;
  87939. y_step = 1;
  87940. y_end = header.height;
  87941. break;
  87942. case TGATools._ORIGIN_BL:
  87943. x_start = 0;
  87944. x_step = 1;
  87945. x_end = header.width;
  87946. y_start = header.height - 1;
  87947. y_step = -1;
  87948. y_end = -1;
  87949. break;
  87950. case TGATools._ORIGIN_UR:
  87951. x_start = header.width - 1;
  87952. x_step = -1;
  87953. x_end = -1;
  87954. y_start = 0;
  87955. y_step = 1;
  87956. y_end = header.height;
  87957. break;
  87958. case TGATools._ORIGIN_BR:
  87959. x_start = header.width - 1;
  87960. x_step = -1;
  87961. x_end = -1;
  87962. y_start = header.height - 1;
  87963. y_step = -1;
  87964. y_end = -1;
  87965. break;
  87966. }
  87967. // Load the specify method
  87968. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  87969. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  87970. var engine = texture.getEngine();
  87971. engine._uploadDataToTextureDirectly(texture, imageData);
  87972. };
  87973. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87974. var image = pixel_data, colormap = palettes;
  87975. var width = header.width, height = header.height;
  87976. var color, i = 0, x, y;
  87977. var imageData = new Uint8Array(width * height * 4);
  87978. for (y = y_start; y !== y_end; y += y_step) {
  87979. for (x = x_start; x !== x_end; x += x_step, i++) {
  87980. color = image[i];
  87981. imageData[(x + width * y) * 4 + 3] = 255;
  87982. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  87983. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  87984. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  87985. }
  87986. }
  87987. return imageData;
  87988. };
  87989. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87990. var image = pixel_data;
  87991. var width = header.width, height = header.height;
  87992. var color, i = 0, x, y;
  87993. var imageData = new Uint8Array(width * height * 4);
  87994. for (y = y_start; y !== y_end; y += y_step) {
  87995. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87996. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  87997. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  87998. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  87999. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  88000. imageData[(x + width * y) * 4 + 0] = r;
  88001. imageData[(x + width * y) * 4 + 1] = g;
  88002. imageData[(x + width * y) * 4 + 2] = b;
  88003. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  88004. }
  88005. }
  88006. return imageData;
  88007. };
  88008. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88009. var image = pixel_data;
  88010. var width = header.width, height = header.height;
  88011. var i = 0, x, y;
  88012. var imageData = new Uint8Array(width * height * 4);
  88013. for (y = y_start; y !== y_end; y += y_step) {
  88014. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  88015. imageData[(x + width * y) * 4 + 3] = 255;
  88016. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88017. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88018. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88019. }
  88020. }
  88021. return imageData;
  88022. };
  88023. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88024. var image = pixel_data;
  88025. var width = header.width, height = header.height;
  88026. var i = 0, x, y;
  88027. var imageData = new Uint8Array(width * height * 4);
  88028. for (y = y_start; y !== y_end; y += y_step) {
  88029. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  88030. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88031. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88032. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88033. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  88034. }
  88035. }
  88036. return imageData;
  88037. };
  88038. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88039. var image = pixel_data;
  88040. var width = header.width, height = header.height;
  88041. var color, i = 0, x, y;
  88042. var imageData = new Uint8Array(width * height * 4);
  88043. for (y = y_start; y !== y_end; y += y_step) {
  88044. for (x = x_start; x !== x_end; x += x_step, i++) {
  88045. color = image[i];
  88046. imageData[(x + width * y) * 4 + 0] = color;
  88047. imageData[(x + width * y) * 4 + 1] = color;
  88048. imageData[(x + width * y) * 4 + 2] = color;
  88049. imageData[(x + width * y) * 4 + 3] = 255;
  88050. }
  88051. }
  88052. return imageData;
  88053. };
  88054. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88055. var image = pixel_data;
  88056. var width = header.width, height = header.height;
  88057. var i = 0, x, y;
  88058. var imageData = new Uint8Array(width * height * 4);
  88059. for (y = y_start; y !== y_end; y += y_step) {
  88060. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88061. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  88062. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  88063. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88064. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  88065. }
  88066. }
  88067. return imageData;
  88068. };
  88069. //private static _TYPE_NO_DATA = 0;
  88070. TGATools._TYPE_INDEXED = 1;
  88071. TGATools._TYPE_RGB = 2;
  88072. TGATools._TYPE_GREY = 3;
  88073. TGATools._TYPE_RLE_INDEXED = 9;
  88074. TGATools._TYPE_RLE_RGB = 10;
  88075. TGATools._TYPE_RLE_GREY = 11;
  88076. TGATools._ORIGIN_MASK = 0x30;
  88077. TGATools._ORIGIN_SHIFT = 0x04;
  88078. TGATools._ORIGIN_BL = 0x00;
  88079. TGATools._ORIGIN_BR = 0x01;
  88080. TGATools._ORIGIN_UL = 0x02;
  88081. TGATools._ORIGIN_UR = 0x03;
  88082. return TGATools;
  88083. }());
  88084. BABYLON.TGATools = TGATools;
  88085. })(BABYLON || (BABYLON = {}));
  88086. //# sourceMappingURL=babylon.tga.js.map
  88087. var BABYLON;
  88088. (function (BABYLON) {
  88089. /**
  88090. * Implementation of the TGA Texture Loader.
  88091. */
  88092. var TGATextureLoader = /** @class */ (function () {
  88093. function TGATextureLoader() {
  88094. /**
  88095. * Defines wether the loader supports cascade loading the different faces.
  88096. */
  88097. this.supportCascades = false;
  88098. }
  88099. /**
  88100. * This returns if the loader support the current file information.
  88101. * @param extension defines the file extension of the file being loaded
  88102. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88103. * @param fallback defines the fallback internal texture if any
  88104. * @param isBase64 defines whether the texture is encoded as a base64
  88105. * @param isBuffer defines whether the texture data are stored as a buffer
  88106. * @returns true if the loader can load the specified file
  88107. */
  88108. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88109. return extension.indexOf(".tga") === 0;
  88110. };
  88111. /**
  88112. * Transform the url before loading if required.
  88113. * @param rootUrl the url of the texture
  88114. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88115. * @returns the transformed texture
  88116. */
  88117. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88118. return rootUrl;
  88119. };
  88120. /**
  88121. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88122. * @param rootUrl the url of the texture
  88123. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88124. * @returns the fallback texture
  88125. */
  88126. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88127. return null;
  88128. };
  88129. /**
  88130. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88131. * @param data contains the texture data
  88132. * @param texture defines the BabylonJS internal texture
  88133. * @param createPolynomials will be true if polynomials have been requested
  88134. * @param onLoad defines the callback to trigger once the texture is ready
  88135. * @param onError defines the callback to trigger in case of error
  88136. */
  88137. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88138. throw ".env not supported in Cube.";
  88139. };
  88140. /**
  88141. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88142. * @param data contains the texture data
  88143. * @param texture defines the BabylonJS internal texture
  88144. * @param callback defines the method to call once ready to upload
  88145. */
  88146. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  88147. var uintData = new Uint8Array(data);
  88148. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  88149. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  88150. BABYLON.TGATools.UploadContent(texture, uintData);
  88151. });
  88152. };
  88153. return TGATextureLoader;
  88154. }());
  88155. // Register the loader.
  88156. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  88157. })(BABYLON || (BABYLON = {}));
  88158. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  88159. var BABYLON;
  88160. (function (BABYLON) {
  88161. /**
  88162. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  88163. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  88164. */
  88165. var KhronosTextureContainer = /** @class */ (function () {
  88166. /**
  88167. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  88168. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  88169. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  88170. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  88171. */
  88172. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  88173. this.arrayBuffer = arrayBuffer;
  88174. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  88175. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  88176. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  88177. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  88178. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  88179. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  88180. BABYLON.Tools.Error("texture missing KTX identifier");
  88181. return;
  88182. }
  88183. // load the reset of the header in native 32 bit int
  88184. var header = new Int32Array(this.arrayBuffer, 12, 13);
  88185. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  88186. var oppositeEndianess = header[0] === 0x01020304;
  88187. // read all the header elements in order they exist in the file, without modification (sans endainness)
  88188. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  88189. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  88190. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  88191. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  88192. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  88193. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  88194. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  88195. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  88196. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  88197. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  88198. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  88199. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  88200. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  88201. if (this.glType !== 0) {
  88202. BABYLON.Tools.Error("only compressed formats currently supported");
  88203. return;
  88204. }
  88205. else {
  88206. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  88207. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  88208. }
  88209. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  88210. BABYLON.Tools.Error("only 2D textures currently supported");
  88211. return;
  88212. }
  88213. if (this.numberOfArrayElements !== 0) {
  88214. BABYLON.Tools.Error("texture arrays not currently supported");
  88215. return;
  88216. }
  88217. if (this.numberOfFaces !== facesExpected) {
  88218. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  88219. return;
  88220. }
  88221. // we now have a completely validated file, so could use existence of loadType as success
  88222. // would need to make this more elaborate & adjust checks above to support more than one load type
  88223. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  88224. }
  88225. // not as fast hardware based, but will probably never need to use
  88226. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  88227. return ((val & 0xFF) << 24)
  88228. | ((val & 0xFF00) << 8)
  88229. | ((val >> 8) & 0xFF00)
  88230. | ((val >> 24) & 0xFF);
  88231. };
  88232. /**
  88233. * Uploads KTX content to a Babylon Texture.
  88234. * It is assumed that the texture has already been created & is currently bound
  88235. * @hidden
  88236. */
  88237. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  88238. switch (this.loadType) {
  88239. case KhronosTextureContainer.COMPRESSED_2D:
  88240. this._upload2DCompressedLevels(texture, loadMipmaps);
  88241. break;
  88242. case KhronosTextureContainer.TEX_2D:
  88243. case KhronosTextureContainer.COMPRESSED_3D:
  88244. case KhronosTextureContainer.TEX_3D:
  88245. }
  88246. };
  88247. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  88248. // initialize width & height for level 1
  88249. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  88250. var width = this.pixelWidth;
  88251. var height = this.pixelHeight;
  88252. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  88253. for (var level = 0; level < mipmapCount; level++) {
  88254. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  88255. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  88256. for (var face = 0; face < this.numberOfFaces; face++) {
  88257. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  88258. var engine = texture.getEngine();
  88259. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  88260. dataOffset += imageSize; // add size of the image for the next face/mipmap
  88261. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  88262. }
  88263. width = Math.max(1.0, width * 0.5);
  88264. height = Math.max(1.0, height * 0.5);
  88265. }
  88266. };
  88267. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  88268. // load types
  88269. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  88270. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  88271. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  88272. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  88273. return KhronosTextureContainer;
  88274. }());
  88275. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  88276. })(BABYLON || (BABYLON = {}));
  88277. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  88278. var BABYLON;
  88279. (function (BABYLON) {
  88280. /**
  88281. * Implementation of the KTX Texture Loader.
  88282. */
  88283. var KTXTextureLoader = /** @class */ (function () {
  88284. function KTXTextureLoader() {
  88285. /**
  88286. * Defines wether the loader supports cascade loading the different faces.
  88287. */
  88288. this.supportCascades = false;
  88289. }
  88290. /**
  88291. * This returns if the loader support the current file information.
  88292. * @param extension defines the file extension of the file being loaded
  88293. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88294. * @param fallback defines the fallback internal texture if any
  88295. * @param isBase64 defines whether the texture is encoded as a base64
  88296. * @param isBuffer defines whether the texture data are stored as a buffer
  88297. * @returns true if the loader can load the specified file
  88298. */
  88299. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88300. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  88301. return true;
  88302. }
  88303. return false;
  88304. };
  88305. /**
  88306. * Transform the url before loading if required.
  88307. * @param rootUrl the url of the texture
  88308. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88309. * @returns the transformed texture
  88310. */
  88311. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88312. var lastDot = rootUrl.lastIndexOf('.');
  88313. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  88314. };
  88315. /**
  88316. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88317. * @param rootUrl the url of the texture
  88318. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88319. * @returns the fallback texture
  88320. */
  88321. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88322. // remove the format appended to the rootUrl in the original createCubeTexture call.
  88323. var exp = new RegExp("" + textureFormatInUse + "$");
  88324. return rootUrl.replace(exp, "");
  88325. };
  88326. /**
  88327. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88328. * @param data contains the texture data
  88329. * @param texture defines the BabylonJS internal texture
  88330. * @param createPolynomials will be true if polynomials have been requested
  88331. * @param onLoad defines the callback to trigger once the texture is ready
  88332. * @param onError defines the callback to trigger in case of error
  88333. */
  88334. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88335. if (Array.isArray(data)) {
  88336. return;
  88337. }
  88338. var engine = texture.getEngine();
  88339. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  88340. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  88341. engine._unpackFlipY(true);
  88342. ktx.uploadLevels(texture, texture.generateMipMaps);
  88343. texture.width = ktx.pixelWidth;
  88344. texture.height = ktx.pixelHeight;
  88345. engine._setCubeMapTextureParams(loadMipmap);
  88346. texture.isReady = true;
  88347. };
  88348. /**
  88349. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88350. * @param data contains the texture data
  88351. * @param texture defines the BabylonJS internal texture
  88352. * @param callback defines the method to call once ready to upload
  88353. */
  88354. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  88355. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  88356. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  88357. ktx.uploadLevels(texture, texture.generateMipMaps);
  88358. });
  88359. };
  88360. return KTXTextureLoader;
  88361. }());
  88362. // Register the loader.
  88363. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  88364. })(BABYLON || (BABYLON = {}));
  88365. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  88366. var BABYLON;
  88367. (function (BABYLON) {
  88368. /**
  88369. * Sets of helpers addressing the serialization and deserialization of environment texture
  88370. * stored in a BabylonJS env file.
  88371. * Those files are usually stored as .env files.
  88372. */
  88373. var EnvironmentTextureTools = /** @class */ (function () {
  88374. function EnvironmentTextureTools() {
  88375. }
  88376. /**
  88377. * Gets the environment info from an env file.
  88378. * @param data The array buffer containing the .env bytes.
  88379. * @returns the environment file info (the json header) if successfully parsed.
  88380. */
  88381. EnvironmentTextureTools.GetEnvInfo = function (data) {
  88382. var dataView = new DataView(data);
  88383. var pos = 0;
  88384. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  88385. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  88386. BABYLON.Tools.Error('Not a babylon environment map');
  88387. return null;
  88388. }
  88389. }
  88390. // Read json manifest - collect characters up to null terminator
  88391. var manifestString = '';
  88392. var charCode = 0x00;
  88393. while ((charCode = dataView.getUint8(pos++))) {
  88394. manifestString += String.fromCharCode(charCode);
  88395. }
  88396. var manifest = JSON.parse(manifestString);
  88397. if (manifest.specular) {
  88398. // Extend the header with the position of the payload.
  88399. manifest.specular.specularDataPosition = pos;
  88400. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  88401. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  88402. }
  88403. return manifest;
  88404. };
  88405. /**
  88406. * Creates an environment texture from a loaded cube texture.
  88407. * @param texture defines the cube texture to convert in env file
  88408. * @return a promise containing the environment data if succesfull.
  88409. */
  88410. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  88411. var _this = this;
  88412. var internalTexture = texture.getInternalTexture();
  88413. if (!internalTexture) {
  88414. return Promise.reject("The cube texture is invalid.");
  88415. }
  88416. if (!texture._prefiltered) {
  88417. return Promise.reject("The cube texture is invalid (not prefiltered).");
  88418. }
  88419. var engine = internalTexture.getEngine();
  88420. if (engine && engine.premultipliedAlpha) {
  88421. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  88422. }
  88423. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  88424. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  88425. }
  88426. var canvas = engine.getRenderingCanvas();
  88427. if (!canvas) {
  88428. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  88429. }
  88430. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88431. if (!engine.getCaps().textureFloatRender) {
  88432. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88433. if (!engine.getCaps().textureHalfFloatRender) {
  88434. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  88435. }
  88436. }
  88437. var cubeWidth = internalTexture.width;
  88438. var hostingScene = new BABYLON.Scene(engine);
  88439. var specularTextures = {};
  88440. var promises = [];
  88441. // Read and collect all mipmaps data from the cube.
  88442. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  88443. mipmapsCount = Math.round(mipmapsCount);
  88444. var _loop_1 = function (i) {
  88445. var faceWidth = Math.pow(2, mipmapsCount - i);
  88446. var _loop_2 = function (face) {
  88447. var data = texture.readPixels(face, i);
  88448. // Creates a temp texture with the face data.
  88449. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  88450. // And rgbdEncode them.
  88451. var promise = new Promise(function (resolve, reject) {
  88452. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  88453. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  88454. rgbdPostProcess.onApply = function (effect) {
  88455. effect._bindTexture("textureSampler", tempTexture);
  88456. };
  88457. // As the process needs to happen on the main canvas, keep track of the current size
  88458. var currentW = engine.getRenderWidth();
  88459. var currentH = engine.getRenderHeight();
  88460. // Set the desired size for the texture
  88461. engine.setSize(faceWidth, faceWidth);
  88462. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  88463. // Reading datas from WebGL
  88464. BABYLON.Tools.ToBlob(canvas, function (blob) {
  88465. var fileReader = new FileReader();
  88466. fileReader.onload = function (event) {
  88467. var arrayBuffer = event.target.result;
  88468. specularTextures[i * 6 + face] = arrayBuffer;
  88469. resolve();
  88470. };
  88471. fileReader.readAsArrayBuffer(blob);
  88472. });
  88473. // Reapply the previous canvas size
  88474. engine.setSize(currentW, currentH);
  88475. });
  88476. });
  88477. promises.push(promise);
  88478. };
  88479. // All faces of the cube.
  88480. for (var face = 0; face < 6; face++) {
  88481. _loop_2(face);
  88482. }
  88483. };
  88484. for (var i = 0; i <= mipmapsCount; i++) {
  88485. _loop_1(i);
  88486. }
  88487. // Once all the textures haves been collected as RGBD stored in PNGs
  88488. return Promise.all(promises).then(function () {
  88489. // We can delete the hosting scene keeping track of all the creation objects
  88490. hostingScene.dispose();
  88491. // Creates the json header for the env texture
  88492. var info = {
  88493. version: 1,
  88494. width: cubeWidth,
  88495. irradiance: _this._CreateEnvTextureIrradiance(texture),
  88496. specular: {
  88497. mipmaps: [],
  88498. lodGenerationScale: texture.lodGenerationScale
  88499. }
  88500. };
  88501. // Sets the specular image data information
  88502. var position = 0;
  88503. for (var i = 0; i <= mipmapsCount; i++) {
  88504. for (var face = 0; face < 6; face++) {
  88505. var byteLength = specularTextures[i * 6 + face].byteLength;
  88506. info.specular.mipmaps.push({
  88507. length: byteLength,
  88508. position: position
  88509. });
  88510. position += byteLength;
  88511. }
  88512. }
  88513. // Encode the JSON as an array buffer
  88514. var infoString = JSON.stringify(info);
  88515. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  88516. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  88517. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  88518. infoView[i] = infoString.charCodeAt(i);
  88519. }
  88520. // Ends up with a null terminator for easier parsing
  88521. infoView[infoString.length] = 0x00;
  88522. // Computes the final required size and creates the storage
  88523. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  88524. var finalBuffer = new ArrayBuffer(totalSize);
  88525. var finalBufferView = new Uint8Array(finalBuffer);
  88526. var dataView = new DataView(finalBuffer);
  88527. // Copy the magic bytes identifying the file in
  88528. var pos = 0;
  88529. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  88530. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  88531. }
  88532. // Add the json info
  88533. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  88534. pos += infoBuffer.byteLength;
  88535. // Finally inserts the texture data
  88536. for (var i = 0; i <= mipmapsCount; i++) {
  88537. for (var face = 0; face < 6; face++) {
  88538. var dataBuffer = specularTextures[i * 6 + face];
  88539. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  88540. pos += dataBuffer.byteLength;
  88541. }
  88542. }
  88543. // Voila
  88544. return finalBuffer;
  88545. });
  88546. };
  88547. /**
  88548. * Creates a JSON representation of the spherical data.
  88549. * @param texture defines the texture containing the polynomials
  88550. * @return the JSON representation of the spherical info
  88551. */
  88552. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  88553. var polynmials = texture.sphericalPolynomial;
  88554. if (polynmials == null) {
  88555. return null;
  88556. }
  88557. return {
  88558. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  88559. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  88560. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  88561. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  88562. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  88563. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  88564. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  88565. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  88566. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  88567. };
  88568. };
  88569. /**
  88570. * Uploads the texture info contained in the env file to the GPU.
  88571. * @param texture defines the internal texture to upload to
  88572. * @param arrayBuffer defines the buffer cotaining the data to load
  88573. * @param info defines the texture info retrieved through the GetEnvInfo method
  88574. * @returns a promise
  88575. */
  88576. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  88577. if (info.version !== 1) {
  88578. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  88579. }
  88580. var specularInfo = info.specular;
  88581. if (!specularInfo) {
  88582. // Nothing else parsed so far
  88583. return Promise.resolve();
  88584. }
  88585. // Double checks the enclosed info
  88586. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  88587. mipmapsCount = Math.round(mipmapsCount) + 1;
  88588. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  88589. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  88590. }
  88591. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  88592. var imageData = new Array(mipmapsCount);
  88593. for (var i = 0; i < mipmapsCount; i++) {
  88594. imageData[i] = new Array(6);
  88595. for (var face = 0; face < 6; face++) {
  88596. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  88597. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  88598. }
  88599. }
  88600. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  88601. };
  88602. /**
  88603. * Uploads the levels of image data to the GPU.
  88604. * @param texture defines the internal texture to upload to
  88605. * @param imageData defines the array buffer views of image data [mipmap][face]
  88606. * @returns a promise
  88607. */
  88608. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  88609. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  88610. throw new Error("Texture size must be a power of two");
  88611. }
  88612. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  88613. // Gets everything ready.
  88614. var engine = texture.getEngine();
  88615. var expandTexture = false;
  88616. var generateNonLODTextures = false;
  88617. var rgbdPostProcess = null;
  88618. var cubeRtt = null;
  88619. var lodTextures = null;
  88620. var caps = engine.getCaps();
  88621. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88622. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88623. texture.generateMipMaps = true;
  88624. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  88625. // Add extra process if texture lod is not supported
  88626. if (!caps.textureLOD) {
  88627. expandTexture = false;
  88628. generateNonLODTextures = true;
  88629. lodTextures = {};
  88630. }
  88631. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  88632. else if (engine.webGLVersion < 2) {
  88633. expandTexture = false;
  88634. }
  88635. // If half float available we can uncompress the texture
  88636. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  88637. expandTexture = true;
  88638. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88639. }
  88640. // If full float available we can uncompress the texture
  88641. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  88642. expandTexture = true;
  88643. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88644. }
  88645. // Expand the texture if possible
  88646. if (expandTexture) {
  88647. // Simply run through the decode PP
  88648. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  88649. texture._isRGBD = false;
  88650. texture.invertY = false;
  88651. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  88652. generateDepthBuffer: false,
  88653. generateMipMaps: true,
  88654. generateStencilBuffer: false,
  88655. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  88656. type: texture.type,
  88657. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  88658. });
  88659. }
  88660. else {
  88661. texture._isRGBD = true;
  88662. texture.invertY = true;
  88663. // In case of missing support, applies the same patch than DDS files.
  88664. if (generateNonLODTextures) {
  88665. var mipSlices = 3;
  88666. var scale = texture._lodGenerationScale;
  88667. var offset = texture._lodGenerationOffset;
  88668. for (var i = 0; i < mipSlices; i++) {
  88669. //compute LOD from even spacing in smoothness (matching shader calculation)
  88670. var smoothness = i / (mipSlices - 1);
  88671. var roughness = 1 - smoothness;
  88672. var minLODIndex = offset; // roughness = 0
  88673. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  88674. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  88675. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  88676. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  88677. glTextureFromLod.isCube = true;
  88678. glTextureFromLod.invertY = true;
  88679. glTextureFromLod.generateMipMaps = false;
  88680. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  88681. // Wrap in a base texture for easy binding.
  88682. var lodTexture = new BABYLON.BaseTexture(null);
  88683. lodTexture.isCube = true;
  88684. lodTexture._texture = glTextureFromLod;
  88685. lodTextures[mipmapIndex] = lodTexture;
  88686. switch (i) {
  88687. case 0:
  88688. texture._lodTextureLow = lodTexture;
  88689. break;
  88690. case 1:
  88691. texture._lodTextureMid = lodTexture;
  88692. break;
  88693. case 2:
  88694. texture._lodTextureHigh = lodTexture;
  88695. break;
  88696. }
  88697. }
  88698. }
  88699. }
  88700. var promises = [];
  88701. var _loop_3 = function (i) {
  88702. var _loop_4 = function (face) {
  88703. // Constructs an image element from image data
  88704. var bytes = imageData[i][face];
  88705. var blob = new Blob([bytes], { type: 'image/png' });
  88706. var url = URL.createObjectURL(blob);
  88707. var image = new Image();
  88708. image.src = url;
  88709. // Enqueue promise to upload to the texture.
  88710. var promise = new Promise(function (resolve, reject) {
  88711. image.onload = function () {
  88712. if (expandTexture) {
  88713. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  88714. reject(message);
  88715. }, image);
  88716. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  88717. // Uncompress the data to a RTT
  88718. rgbdPostProcess.onApply = function (effect) {
  88719. effect._bindTexture("textureSampler", tempTexture_1);
  88720. effect.setFloat2("scale", 1, 1);
  88721. };
  88722. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  88723. // Cleanup
  88724. engine.restoreDefaultFramebuffer();
  88725. tempTexture_1.dispose();
  88726. window.URL.revokeObjectURL(url);
  88727. resolve();
  88728. });
  88729. }
  88730. else {
  88731. engine._uploadImageToTexture(texture, image, face, i);
  88732. // Upload the face to the non lod texture support
  88733. if (generateNonLODTextures) {
  88734. var lodTexture = lodTextures[i];
  88735. if (lodTexture) {
  88736. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  88737. }
  88738. }
  88739. resolve();
  88740. }
  88741. };
  88742. image.onerror = function (error) {
  88743. reject(error);
  88744. };
  88745. });
  88746. promises.push(promise);
  88747. };
  88748. // All faces
  88749. for (var face = 0; face < 6; face++) {
  88750. _loop_4(face);
  88751. }
  88752. };
  88753. // All mipmaps up to provided number of images
  88754. for (var i = 0; i < imageData.length; i++) {
  88755. _loop_3(i);
  88756. }
  88757. // Fill remaining mipmaps with black textures.
  88758. if (imageData.length < mipmapsCount) {
  88759. var data = void 0;
  88760. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  88761. var dataLength = size * size * 4;
  88762. switch (texture.type) {
  88763. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  88764. data = new Uint8Array(dataLength);
  88765. break;
  88766. }
  88767. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  88768. data = new Uint16Array(dataLength);
  88769. break;
  88770. }
  88771. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  88772. data = new Float32Array(dataLength);
  88773. break;
  88774. }
  88775. }
  88776. for (var i = imageData.length; i < mipmapsCount; i++) {
  88777. for (var face = 0; face < 6; face++) {
  88778. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  88779. }
  88780. }
  88781. }
  88782. // Once all done, finishes the cleanup and return
  88783. return Promise.all(promises).then(function () {
  88784. // Release temp RTT.
  88785. if (cubeRtt) {
  88786. engine._releaseFramebufferObjects(cubeRtt);
  88787. cubeRtt._swapAndDie(texture);
  88788. }
  88789. // Release temp Post Process.
  88790. if (rgbdPostProcess) {
  88791. rgbdPostProcess.dispose();
  88792. }
  88793. // Flag internal texture as ready in case they are in use.
  88794. if (generateNonLODTextures) {
  88795. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  88796. texture._lodTextureHigh._texture.isReady = true;
  88797. }
  88798. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  88799. texture._lodTextureMid._texture.isReady = true;
  88800. }
  88801. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  88802. texture._lodTextureLow._texture.isReady = true;
  88803. }
  88804. }
  88805. });
  88806. };
  88807. /**
  88808. * Uploads spherical polynomials information to the texture.
  88809. * @param texture defines the texture we are trying to upload the information to
  88810. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  88811. */
  88812. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  88813. if (info.version !== 1) {
  88814. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  88815. }
  88816. var irradianceInfo = info.irradiance;
  88817. if (!irradianceInfo) {
  88818. return;
  88819. }
  88820. var sp = new BABYLON.SphericalPolynomial();
  88821. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  88822. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  88823. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  88824. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  88825. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  88826. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  88827. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  88828. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  88829. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  88830. texture._sphericalPolynomial = sp;
  88831. };
  88832. /**
  88833. * Magic number identifying the env file.
  88834. */
  88835. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  88836. return EnvironmentTextureTools;
  88837. }());
  88838. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  88839. })(BABYLON || (BABYLON = {}));
  88840. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  88841. var BABYLON;
  88842. (function (BABYLON) {
  88843. /**
  88844. * Implementation of the ENV Texture Loader.
  88845. */
  88846. var ENVTextureLoader = /** @class */ (function () {
  88847. function ENVTextureLoader() {
  88848. /**
  88849. * Defines wether the loader supports cascade loading the different faces.
  88850. */
  88851. this.supportCascades = false;
  88852. }
  88853. /**
  88854. * This returns if the loader support the current file information.
  88855. * @param extension defines the file extension of the file being loaded
  88856. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88857. * @param fallback defines the fallback internal texture if any
  88858. * @param isBase64 defines whether the texture is encoded as a base64
  88859. * @param isBuffer defines whether the texture data are stored as a buffer
  88860. * @returns true if the loader can load the specified file
  88861. */
  88862. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88863. return extension.indexOf(".env") === 0;
  88864. };
  88865. /**
  88866. * Transform the url before loading if required.
  88867. * @param rootUrl the url of the texture
  88868. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88869. * @returns the transformed texture
  88870. */
  88871. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88872. return rootUrl;
  88873. };
  88874. /**
  88875. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88876. * @param rootUrl the url of the texture
  88877. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88878. * @returns the fallback texture
  88879. */
  88880. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88881. return null;
  88882. };
  88883. /**
  88884. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88885. * @param data contains the texture data
  88886. * @param texture defines the BabylonJS internal texture
  88887. * @param createPolynomials will be true if polynomials have been requested
  88888. * @param onLoad defines the callback to trigger once the texture is ready
  88889. * @param onError defines the callback to trigger in case of error
  88890. */
  88891. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88892. if (Array.isArray(data)) {
  88893. return;
  88894. }
  88895. data = data;
  88896. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  88897. if (info) {
  88898. texture.width = info.width;
  88899. texture.height = info.width;
  88900. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  88901. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  88902. texture.isReady = true;
  88903. if (onLoad) {
  88904. onLoad();
  88905. }
  88906. });
  88907. }
  88908. else if (onError) {
  88909. onError("Can not parse the environment file", null);
  88910. }
  88911. };
  88912. /**
  88913. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88914. * @param data contains the texture data
  88915. * @param texture defines the BabylonJS internal texture
  88916. * @param callback defines the method to call once ready to upload
  88917. */
  88918. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  88919. throw ".env not supported in 2d.";
  88920. };
  88921. return ENVTextureLoader;
  88922. }());
  88923. // Register the loader.
  88924. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  88925. })(BABYLON || (BABYLON = {}));
  88926. //# sourceMappingURL=babylon.envTextureLoader.js.map
  88927. var BABYLON;
  88928. (function (BABYLON) {
  88929. /**
  88930. * Renders a layer on top of an existing scene
  88931. */
  88932. var UtilityLayerRenderer = /** @class */ (function () {
  88933. /**
  88934. * Instantiates a UtilityLayerRenderer
  88935. * @param originalScene the original scene that will be rendered on top of
  88936. */
  88937. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88938. var _this = this;
  88939. this.originalScene = originalScene;
  88940. this._pointerCaptures = {};
  88941. this._lastPointerEvents = {};
  88942. /**
  88943. * If the utility layer should automatically be rendered on top of existing scene
  88944. */
  88945. this.shouldRender = true;
  88946. /**
  88947. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88948. */
  88949. this.onlyCheckPointerDownEvents = true;
  88950. /**
  88951. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88952. */
  88953. this.processAllEvents = false;
  88954. /**
  88955. * Observable raised when the pointer move from the utility layer scene to the main scene
  88956. */
  88957. this.onPointerOutObservable = new BABYLON.Observable();
  88958. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88959. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88960. this.utilityLayerScene._allowPostProcessClear = false;
  88961. originalScene.getEngine().scenes.pop();
  88962. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88963. this.utilityLayerScene.detachControl();
  88964. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88965. if (!_this.processAllEvents) {
  88966. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88967. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88968. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88969. return;
  88970. }
  88971. }
  88972. var pointerEvent = (prePointerInfo.event);
  88973. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88974. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88975. return;
  88976. }
  88977. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88978. if (!prePointerInfo.ray && utilityScenePick) {
  88979. prePointerInfo.ray = utilityScenePick.ray;
  88980. }
  88981. // always fire the prepointer oversvable
  88982. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88983. // allow every non pointer down event to flow to the utility layer
  88984. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88985. if (!prePointerInfo.skipOnPointerObservable) {
  88986. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88987. }
  88988. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88989. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88990. }
  88991. return;
  88992. }
  88993. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88994. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88995. if (utilityScenePick && utilityScenePick.hit) {
  88996. if (!prePointerInfo.skipOnPointerObservable) {
  88997. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88998. }
  88999. prePointerInfo.skipOnPointerObservable = true;
  89000. }
  89001. }
  89002. else {
  89003. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  89004. var pointerEvent_1 = (prePointerInfo.event);
  89005. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  89006. if (originalScenePick && utilityScenePick) {
  89007. // No pick in utility scene
  89008. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  89009. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89010. // We touched an utility mesh present in the main scene
  89011. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89012. prePointerInfo.skipOnPointerObservable = true;
  89013. }
  89014. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89015. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  89016. }
  89017. }
  89018. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  89019. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  89020. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  89021. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  89022. }
  89023. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  89024. // We have a pick in both scenes but main is closer than utility
  89025. // We touched an utility mesh present in the main scene
  89026. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89027. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89028. prePointerInfo.skipOnPointerObservable = true;
  89029. }
  89030. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  89031. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  89032. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  89033. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  89034. }
  89035. }
  89036. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  89037. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  89038. }
  89039. }
  89040. }
  89041. });
  89042. // Render directly on top of existing scene without clearing
  89043. this.utilityLayerScene.autoClear = false;
  89044. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  89045. if (_this.shouldRender) {
  89046. _this.render();
  89047. }
  89048. });
  89049. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  89050. _this.dispose();
  89051. });
  89052. this._updateCamera();
  89053. }
  89054. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  89055. /**
  89056. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  89057. */
  89058. get: function () {
  89059. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  89060. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89061. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89062. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89063. });
  89064. }
  89065. return UtilityLayerRenderer._DefaultUtilityLayer;
  89066. },
  89067. enumerable: true,
  89068. configurable: true
  89069. });
  89070. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  89071. /**
  89072. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  89073. */
  89074. get: function () {
  89075. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  89076. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89077. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  89078. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89079. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89080. });
  89081. }
  89082. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  89083. },
  89084. enumerable: true,
  89085. configurable: true
  89086. });
  89087. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  89088. if (!prePointerInfo.skipOnPointerObservable) {
  89089. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  89090. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  89091. }
  89092. };
  89093. /**
  89094. * Renders the utility layers scene on top of the original scene
  89095. */
  89096. UtilityLayerRenderer.prototype.render = function () {
  89097. this._updateCamera();
  89098. if (this.utilityLayerScene.activeCamera) {
  89099. // Set the camera's scene to utility layers scene
  89100. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  89101. var camera = this.utilityLayerScene.activeCamera;
  89102. camera._scene = this.utilityLayerScene;
  89103. if (camera.leftCamera) {
  89104. camera.leftCamera._scene = this.utilityLayerScene;
  89105. }
  89106. if (camera.rightCamera) {
  89107. camera.rightCamera._scene = this.utilityLayerScene;
  89108. }
  89109. this.utilityLayerScene.render(false);
  89110. // Reset camera's scene back to original
  89111. camera._scene = oldScene;
  89112. if (camera.leftCamera) {
  89113. camera.leftCamera._scene = oldScene;
  89114. }
  89115. if (camera.rightCamera) {
  89116. camera.rightCamera._scene = oldScene;
  89117. }
  89118. }
  89119. };
  89120. /**
  89121. * Disposes of the renderer
  89122. */
  89123. UtilityLayerRenderer.prototype.dispose = function () {
  89124. this.onPointerOutObservable.clear();
  89125. if (this._afterRenderObserver) {
  89126. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  89127. }
  89128. if (this._sceneDisposeObserver) {
  89129. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89130. }
  89131. if (this._originalPointerObserver) {
  89132. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  89133. }
  89134. this.utilityLayerScene.dispose();
  89135. };
  89136. UtilityLayerRenderer.prototype._updateCamera = function () {
  89137. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  89138. };
  89139. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89140. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89141. return UtilityLayerRenderer;
  89142. }());
  89143. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  89144. })(BABYLON || (BABYLON = {}));
  89145. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  89146. //# sourceMappingURL=babylon.behavior.js.map
  89147. var BABYLON;
  89148. (function (BABYLON) {
  89149. /**
  89150. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  89151. */
  89152. var PointerDragBehavior = /** @class */ (function () {
  89153. /**
  89154. * Creates a pointer drag behavior that can be attached to a mesh
  89155. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  89156. */
  89157. function PointerDragBehavior(options) {
  89158. /**
  89159. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  89160. */
  89161. this.maxDragAngle = 0;
  89162. /**
  89163. * @hidden
  89164. */
  89165. this._useAlternatePickedPointAboveMaxDragAngle = false;
  89166. /**
  89167. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89168. */
  89169. this.currentDraggingPointerID = -1;
  89170. /**
  89171. * If the behavior is currently in a dragging state
  89172. */
  89173. this.dragging = false;
  89174. /**
  89175. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  89176. */
  89177. this.dragDeltaRatio = 0.2;
  89178. /**
  89179. * If the drag plane orientation should be updated during the dragging (Default: true)
  89180. */
  89181. this.updateDragPlane = true;
  89182. // Debug mode will display drag planes to help visualize behavior
  89183. this._debugMode = false;
  89184. this._moving = false;
  89185. /**
  89186. * Fires each time the attached mesh is dragged with the pointer
  89187. * * delta between last drag position and current drag position in world space
  89188. * * dragDistance along the drag axis
  89189. * * dragPlaneNormal normal of the current drag plane used during the drag
  89190. * * dragPlanePoint in world space where the drag intersects the drag plane
  89191. */
  89192. this.onDragObservable = new BABYLON.Observable();
  89193. /**
  89194. * Fires each time a drag begins (eg. mouse down on mesh)
  89195. */
  89196. this.onDragStartObservable = new BABYLON.Observable();
  89197. /**
  89198. * Fires each time a drag ends (eg. mouse release after drag)
  89199. */
  89200. this.onDragEndObservable = new BABYLON.Observable();
  89201. /**
  89202. * If the attached mesh should be moved when dragged
  89203. */
  89204. this.moveAttached = true;
  89205. /**
  89206. * If the drag behavior will react to drag events (Default: true)
  89207. */
  89208. this.enabled = true;
  89209. /**
  89210. * If camera controls should be detached during the drag
  89211. */
  89212. this.detachCameraControls = true;
  89213. /**
  89214. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  89215. */
  89216. this.useObjectOrienationForDragging = true;
  89217. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89218. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  89219. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  89220. // Variables to avoid instantiation in the below method
  89221. this._pointA = new BABYLON.Vector3(0, 0, 0);
  89222. this._pointB = new BABYLON.Vector3(0, 0, 0);
  89223. this._pointC = new BABYLON.Vector3(0, 0, 0);
  89224. this._lineA = new BABYLON.Vector3(0, 0, 0);
  89225. this._lineB = new BABYLON.Vector3(0, 0, 0);
  89226. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  89227. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  89228. this._options = options ? options : {};
  89229. var optionCount = 0;
  89230. if (this._options.dragAxis) {
  89231. optionCount++;
  89232. }
  89233. if (this._options.dragPlaneNormal) {
  89234. optionCount++;
  89235. }
  89236. if (optionCount > 1) {
  89237. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  89238. }
  89239. }
  89240. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  89241. /**
  89242. * The name of the behavior
  89243. */
  89244. get: function () {
  89245. return "PointerDrag";
  89246. },
  89247. enumerable: true,
  89248. configurable: true
  89249. });
  89250. /**
  89251. * Initializes the behavior
  89252. */
  89253. PointerDragBehavior.prototype.init = function () { };
  89254. /**
  89255. * Attaches the drag behavior the passed in mesh
  89256. * @param ownerNode The mesh that will be dragged around once attached
  89257. */
  89258. PointerDragBehavior.prototype.attach = function (ownerNode) {
  89259. var _this = this;
  89260. this._scene = ownerNode.getScene();
  89261. this._attachedNode = ownerNode;
  89262. // Initialize drag plane to not interfere with existing scene
  89263. if (!PointerDragBehavior._planeScene) {
  89264. if (this._debugMode) {
  89265. PointerDragBehavior._planeScene = this._scene;
  89266. }
  89267. else {
  89268. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  89269. PointerDragBehavior._planeScene.detachControl();
  89270. this._scene.getEngine().scenes.pop();
  89271. this._scene.onDisposeObservable.addOnce(function () {
  89272. PointerDragBehavior._planeScene.dispose();
  89273. PointerDragBehavior._planeScene = null;
  89274. });
  89275. }
  89276. }
  89277. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  89278. // State of the drag
  89279. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  89280. var delta = new BABYLON.Vector3(0, 0, 0);
  89281. var dragLength = 0;
  89282. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  89283. var pickPredicate = function (m) {
  89284. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  89285. };
  89286. var attachedElement = null;
  89287. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89288. if (!_this.enabled) {
  89289. return;
  89290. }
  89291. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89292. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89293. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  89294. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89295. if (pickedPoint) {
  89296. _this.dragging = true;
  89297. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89298. _this.lastDragPosition.copyFrom(pickedPoint);
  89299. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  89300. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  89301. // Detatch camera controls
  89302. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89303. if (_this._scene.activeCamera.inputs.attachedElement) {
  89304. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  89305. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  89306. }
  89307. else {
  89308. attachedElement = null;
  89309. }
  89310. }
  89311. }
  89312. }
  89313. }
  89314. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89315. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89316. _this.releaseDrag();
  89317. // Reattach camera controls
  89318. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89319. _this._scene.activeCamera.attachControl(attachedElement, true);
  89320. }
  89321. }
  89322. }
  89323. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89324. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89325. _this._moving = true;
  89326. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89327. if (pickedPoint) {
  89328. if (_this.updateDragPlane) {
  89329. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  89330. }
  89331. // depending on the drag mode option drag accordingly
  89332. if (_this._options.dragAxis) {
  89333. // Convert local drag axis to world
  89334. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  89335. // Project delta drag from the drag plane onto the drag axis
  89336. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  89337. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  89338. _this._worldDragAxis.scaleToRef(dragLength, delta);
  89339. }
  89340. else {
  89341. dragLength = delta.length();
  89342. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  89343. }
  89344. targetPosition.addInPlace(delta);
  89345. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  89346. _this.lastDragPosition.copyFrom(pickedPoint);
  89347. }
  89348. }
  89349. }
  89350. });
  89351. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89352. if (_this._moving && _this.moveAttached) {
  89353. // Slowly move mesh to avoid jitter
  89354. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  89355. _this._tmpVector.scaleInPlace(0.2);
  89356. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  89357. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  89358. }
  89359. });
  89360. };
  89361. PointerDragBehavior.prototype.releaseDrag = function () {
  89362. this.dragging = false;
  89363. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  89364. this.currentDraggingPointerID = -1;
  89365. this._moving = false;
  89366. };
  89367. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  89368. var _this = this;
  89369. if (!ray) {
  89370. return null;
  89371. }
  89372. // Calculate angle between plane normal and ray
  89373. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  89374. // Correct if ray is casted from oposite side
  89375. if (angle > Math.PI / 2) {
  89376. angle = Math.PI - angle;
  89377. }
  89378. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  89379. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  89380. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  89381. // Invert ray direction along the towards object axis
  89382. this._tmpVector.copyFrom(ray.direction);
  89383. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  89384. this._alternatePickedPoint.normalize();
  89385. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  89386. this._tmpVector.addInPlace(this._alternatePickedPoint);
  89387. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  89388. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  89389. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  89390. this._alternatePickedPoint.addInPlace(this._tmpVector);
  89391. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  89392. return this._alternatePickedPoint;
  89393. }
  89394. else {
  89395. return null;
  89396. }
  89397. }
  89398. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  89399. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  89400. return pickResult.pickedPoint;
  89401. }
  89402. else {
  89403. return null;
  89404. }
  89405. };
  89406. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  89407. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  89408. this._pointA.copyFrom(dragPlanePosition);
  89409. if (this._options.dragAxis) {
  89410. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  89411. // Calculate plane normal in direction of camera but perpendicular to drag axis
  89412. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  89413. ray.origin.subtractToRef(this._pointA, this._pointC);
  89414. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  89415. // Get perpendicular line from direction to camera and drag axis
  89416. this._pointB.subtractToRef(this._pointA, this._lineA);
  89417. this._pointC.subtractToRef(this._pointA, this._lineB);
  89418. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  89419. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  89420. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  89421. this._lookAt.normalize();
  89422. this._dragPlane.position.copyFrom(this._pointA);
  89423. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  89424. this._dragPlane.lookAt(this._lookAt);
  89425. }
  89426. else if (this._options.dragPlaneNormal) {
  89427. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  89428. this._dragPlane.position.copyFrom(this._pointA);
  89429. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  89430. this._dragPlane.lookAt(this._lookAt);
  89431. }
  89432. else {
  89433. this._dragPlane.position.copyFrom(this._pointA);
  89434. this._dragPlane.lookAt(ray.origin);
  89435. }
  89436. this._dragPlane.computeWorldMatrix(true);
  89437. };
  89438. /**
  89439. * Detaches the behavior from the mesh
  89440. */
  89441. PointerDragBehavior.prototype.detach = function () {
  89442. if (this._pointerObserver) {
  89443. this._scene.onPointerObservable.remove(this._pointerObserver);
  89444. }
  89445. if (this._beforeRenderObserver) {
  89446. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89447. }
  89448. };
  89449. return PointerDragBehavior;
  89450. }());
  89451. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89452. })(BABYLON || (BABYLON = {}));
  89453. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89454. var BABYLON;
  89455. (function (BABYLON) {
  89456. /**
  89457. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89458. */
  89459. var MultiPointerScaleBehavior = /** @class */ (function () {
  89460. function MultiPointerScaleBehavior() {
  89461. this._startDistance = 0;
  89462. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89463. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89464. this._sceneRenderObserver = null;
  89465. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89466. this._dragBehaviorA.moveAttached = false;
  89467. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89468. this._dragBehaviorB.moveAttached = false;
  89469. }
  89470. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89471. /**
  89472. * The name of the behavior
  89473. */
  89474. get: function () {
  89475. return "MultiPointerScale";
  89476. },
  89477. enumerable: true,
  89478. configurable: true
  89479. });
  89480. /**
  89481. * Initializes the behavior
  89482. */
  89483. MultiPointerScaleBehavior.prototype.init = function () { };
  89484. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89485. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89486. };
  89487. /**
  89488. * Attaches the scale behavior the passed in mesh
  89489. * @param ownerNode The mesh that will be scaled around once attached
  89490. */
  89491. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89492. var _this = this;
  89493. this._ownerNode = ownerNode;
  89494. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89495. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89496. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89497. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89498. _this._dragBehaviorA.releaseDrag();
  89499. }
  89500. else {
  89501. _this._initialScale.copyFrom(ownerNode.scaling);
  89502. _this._startDistance = _this._getCurrentDistance();
  89503. }
  89504. }
  89505. });
  89506. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89507. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89508. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89509. _this._dragBehaviorB.releaseDrag();
  89510. }
  89511. else {
  89512. _this._initialScale.copyFrom(ownerNode.scaling);
  89513. _this._startDistance = _this._getCurrentDistance();
  89514. }
  89515. }
  89516. });
  89517. // Once both drag behaviors are active scale based on the distance between the two pointers
  89518. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89519. behavior.onDragObservable.add(function () {
  89520. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89521. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89522. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89523. }
  89524. });
  89525. });
  89526. ownerNode.addBehavior(this._dragBehaviorA);
  89527. ownerNode.addBehavior(this._dragBehaviorB);
  89528. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89529. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89530. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89531. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89532. if (change.length() > 0.01) {
  89533. ownerNode.scaling.addInPlace(change);
  89534. }
  89535. }
  89536. });
  89537. };
  89538. /**
  89539. * Detaches the behavior from the mesh
  89540. */
  89541. MultiPointerScaleBehavior.prototype.detach = function () {
  89542. var _this = this;
  89543. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89544. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89545. behavior.onDragStartObservable.clear();
  89546. behavior.onDragObservable.clear();
  89547. _this._ownerNode.removeBehavior(behavior);
  89548. });
  89549. };
  89550. return MultiPointerScaleBehavior;
  89551. }());
  89552. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89553. })(BABYLON || (BABYLON = {}));
  89554. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89555. var BABYLON;
  89556. (function (BABYLON) {
  89557. /**
  89558. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  89559. */
  89560. var SixDofDragBehavior = /** @class */ (function () {
  89561. function SixDofDragBehavior() {
  89562. this._sceneRenderObserver = null;
  89563. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89564. this._moving = false;
  89565. this._startingOrientation = new BABYLON.Quaternion();
  89566. /**
  89567. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
  89568. */
  89569. this.zDragFactor = 3;
  89570. /**
  89571. * If the behavior is currently in a dragging state
  89572. */
  89573. this.dragging = false;
  89574. /**
  89575. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  89576. */
  89577. this.dragDeltaRatio = 0.2;
  89578. /**
  89579. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89580. */
  89581. this.currentDraggingPointerID = -1;
  89582. /**
  89583. * If camera controls should be detached during the drag
  89584. */
  89585. this.detachCameraControls = true;
  89586. }
  89587. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89588. /**
  89589. * The name of the behavior
  89590. */
  89591. get: function () {
  89592. return "SixDofDrag";
  89593. },
  89594. enumerable: true,
  89595. configurable: true
  89596. });
  89597. /**
  89598. * Initializes the behavior
  89599. */
  89600. SixDofDragBehavior.prototype.init = function () { };
  89601. /**
  89602. * Attaches the scale behavior the passed in mesh
  89603. * @param ownerNode The mesh that will be scaled around once attached
  89604. */
  89605. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89606. var _this = this;
  89607. this._ownerNode = ownerNode;
  89608. this._scene = this._ownerNode.getScene();
  89609. if (!SixDofDragBehavior._virtualScene) {
  89610. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89611. this._scene.getEngine().scenes.pop();
  89612. }
  89613. var pickedMesh = null;
  89614. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89615. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89616. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89617. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89618. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89619. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89620. var pickPredicate = function (m) {
  89621. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89622. };
  89623. var attachedElement = null;
  89624. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89625. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89626. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89627. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89628. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89629. }
  89630. pickedMesh = _this._ownerNode;
  89631. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89632. // Set position and orientation of the controller
  89633. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89634. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89635. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89636. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89637. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89638. if (!pickedMesh.rotationQuaternion) {
  89639. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89640. }
  89641. var oldParent = pickedMesh.parent;
  89642. pickedMesh.setParent(null);
  89643. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89644. pickedMesh.setParent(oldParent);
  89645. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89646. // Update state
  89647. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89648. _this.dragging = true;
  89649. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89650. // Detatch camera controls
  89651. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89652. if (_this._scene.activeCamera.inputs.attachedElement) {
  89653. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  89654. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  89655. }
  89656. else {
  89657. attachedElement = null;
  89658. }
  89659. }
  89660. }
  89661. }
  89662. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89663. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89664. _this.dragging = false;
  89665. _this._moving = false;
  89666. _this.currentDraggingPointerID = -1;
  89667. pickedMesh = null;
  89668. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89669. // Reattach camera controls
  89670. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89671. _this._scene.activeCamera.attachControl(attachedElement, true);
  89672. }
  89673. }
  89674. }
  89675. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89676. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89677. var zDragFactor = _this.zDragFactor;
  89678. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89679. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89680. zDragFactor = 0;
  89681. }
  89682. // Calculate controller drag distance in controller space
  89683. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89684. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89685. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  89686. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89687. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89688. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  89689. if (_this._virtualDragMesh.position.z < 0) {
  89690. _this._virtualDragMesh.position.z = 0;
  89691. }
  89692. // Update the controller position
  89693. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89694. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89695. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89696. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89697. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89698. if (pickedMesh.parent) {
  89699. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89700. }
  89701. if (!_this._moving) {
  89702. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89703. }
  89704. _this._moving = true;
  89705. }
  89706. }
  89707. });
  89708. var tmpQuaternion = new BABYLON.Quaternion();
  89709. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89710. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89711. if (_this.dragging && _this._moving && pickedMesh) {
  89712. // Slowly move mesh to avoid jitter
  89713. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89714. // Get change in rotation
  89715. tmpQuaternion.copyFrom(_this._startingOrientation);
  89716. tmpQuaternion.x = -tmpQuaternion.x;
  89717. tmpQuaternion.y = -tmpQuaternion.y;
  89718. tmpQuaternion.z = -tmpQuaternion.z;
  89719. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89720. // Convert change in rotation to only y axis rotation
  89721. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89722. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89723. // Slowly move mesh to avoid jitter
  89724. var oldParent = pickedMesh.parent;
  89725. pickedMesh.setParent(null);
  89726. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89727. pickedMesh.setParent(oldParent);
  89728. }
  89729. });
  89730. };
  89731. /**
  89732. * Detaches the behavior from the mesh
  89733. */
  89734. SixDofDragBehavior.prototype.detach = function () {
  89735. if (this._scene) {
  89736. this._scene.onPointerObservable.remove(this._pointerObserver);
  89737. }
  89738. if (this._ownerNode) {
  89739. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89740. }
  89741. if (this._virtualOriginMesh) {
  89742. this._virtualOriginMesh.dispose();
  89743. }
  89744. if (this._virtualDragMesh) {
  89745. this._virtualDragMesh.dispose();
  89746. }
  89747. };
  89748. return SixDofDragBehavior;
  89749. }());
  89750. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89751. })(BABYLON || (BABYLON = {}));
  89752. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89753. var BABYLON;
  89754. (function (BABYLON) {
  89755. /**
  89756. * @hidden
  89757. */
  89758. var FaceDirectionInfo = /** @class */ (function () {
  89759. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  89760. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  89761. if (diff === void 0) { diff = 0; }
  89762. if (ignore === void 0) { ignore = false; }
  89763. this.direction = direction;
  89764. this.rotatedDirection = rotatedDirection;
  89765. this.diff = diff;
  89766. this.ignore = ignore;
  89767. }
  89768. return FaceDirectionInfo;
  89769. }());
  89770. /**
  89771. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  89772. */
  89773. var AttachToBoxBehavior = /** @class */ (function () {
  89774. /**
  89775. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  89776. * @param ui The transform node that should be attched to the mesh
  89777. */
  89778. function AttachToBoxBehavior(ui) {
  89779. this.ui = ui;
  89780. /**
  89781. * The name of the behavior
  89782. */
  89783. this.name = "AttachToBoxBehavior";
  89784. /**
  89785. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  89786. */
  89787. this.distanceAwayFromFace = 0.15;
  89788. /**
  89789. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  89790. */
  89791. this.distanceAwayFromBottomOfFace = 0.15;
  89792. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  89793. this._tmpMatrix = new BABYLON.Matrix();
  89794. this._tmpVector = new BABYLON.Vector3();
  89795. this._zeroVector = BABYLON.Vector3.Zero();
  89796. this._lookAtTmpMatrix = new BABYLON.Matrix();
  89797. /* Does nothing */
  89798. }
  89799. /**
  89800. * Initializes the behavior
  89801. */
  89802. AttachToBoxBehavior.prototype.init = function () {
  89803. /* Does nothing */
  89804. };
  89805. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  89806. var _this = this;
  89807. // Go over each face and calculate the angle between the face's normal and targetDirection
  89808. this._faceVectors.forEach(function (v) {
  89809. if (!_this._target.rotationQuaternion) {
  89810. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  89811. }
  89812. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  89813. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  89814. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  89815. });
  89816. // Return the face information of the one with the normal closeset to target direction
  89817. return this._faceVectors.reduce(function (min, p) {
  89818. if (min.ignore) {
  89819. return p;
  89820. }
  89821. else if (p.ignore) {
  89822. return min;
  89823. }
  89824. else {
  89825. return min.diff < p.diff ? min : p;
  89826. }
  89827. }, this._faceVectors[0]);
  89828. };
  89829. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  89830. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  89831. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  89832. this._lookAtTmpMatrix.invert();
  89833. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  89834. };
  89835. /**
  89836. * Attaches the AttachToBoxBehavior to the passed in mesh
  89837. * @param target The mesh that the specified node will be attached to
  89838. */
  89839. AttachToBoxBehavior.prototype.attach = function (target) {
  89840. var _this = this;
  89841. this._target = target;
  89842. this._scene = this._target.getScene();
  89843. // Every frame, update the app bars position
  89844. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89845. if (!_this._scene.activeCamera) {
  89846. return;
  89847. }
  89848. // Find the face closest to the cameras position
  89849. var cameraPos = _this._scene.activeCamera.position;
  89850. if (_this._scene.activeCamera.devicePosition) {
  89851. cameraPos = _this._scene.activeCamera.devicePosition;
  89852. }
  89853. var facing = _this._closestFace(cameraPos.subtract(target.position));
  89854. if (_this._scene.activeCamera.leftCamera) {
  89855. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89856. }
  89857. else {
  89858. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89859. }
  89860. // Get camera up direction
  89861. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  89862. // Ignore faces to not select a parrelel face for the up vector of the UI
  89863. _this._faceVectors.forEach(function (v) {
  89864. if (facing.direction.x && v.direction.x) {
  89865. v.ignore = true;
  89866. }
  89867. if (facing.direction.y && v.direction.y) {
  89868. v.ignore = true;
  89869. }
  89870. if (facing.direction.z && v.direction.z) {
  89871. v.ignore = true;
  89872. }
  89873. });
  89874. var facingUp = _this._closestFace(_this._tmpVector);
  89875. // Unignore faces
  89876. _this._faceVectors.forEach(function (v) {
  89877. v.ignore = false;
  89878. });
  89879. // Position the app bar on that face
  89880. _this.ui.position.copyFrom(target.position);
  89881. if (facing.direction.x) {
  89882. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89883. _this.ui.position.addInPlace(_this._tmpVector);
  89884. }
  89885. if (facing.direction.y) {
  89886. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89887. _this.ui.position.addInPlace(_this._tmpVector);
  89888. }
  89889. if (facing.direction.z) {
  89890. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89891. _this.ui.position.addInPlace(_this._tmpVector);
  89892. }
  89893. // Rotate to be oriented properly to the camera
  89894. if (!_this.ui.rotationQuaternion) {
  89895. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  89896. }
  89897. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  89898. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  89899. // Place ui the correct distance from the bottom of the mesh
  89900. if (facingUp.direction.x) {
  89901. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  89902. }
  89903. if (facingUp.direction.y) {
  89904. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  89905. }
  89906. if (facingUp.direction.z) {
  89907. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  89908. }
  89909. _this.ui.position.addInPlace(_this._tmpVector);
  89910. });
  89911. };
  89912. /**
  89913. * Detaches the behavior from the mesh
  89914. */
  89915. AttachToBoxBehavior.prototype.detach = function () {
  89916. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  89917. };
  89918. return AttachToBoxBehavior;
  89919. }());
  89920. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  89921. })(BABYLON || (BABYLON = {}));
  89922. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  89923. var BABYLON;
  89924. (function (BABYLON) {
  89925. /**
  89926. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89927. */
  89928. var Gizmo = /** @class */ (function () {
  89929. /**
  89930. * Creates a gizmo
  89931. * @param gizmoLayer The utility layer the gizmo will be added to
  89932. */
  89933. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89934. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89935. var _this = this;
  89936. this.gizmoLayer = gizmoLayer;
  89937. this._scaleFactor = 3;
  89938. this._tmpMatrix = new BABYLON.Matrix();
  89939. /**
  89940. * If a custom mesh has been set (Default: false)
  89941. */
  89942. this._customMeshSet = false;
  89943. /**
  89944. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89945. */
  89946. this.updateGizmoRotationToMatchAttachedMesh = true;
  89947. /**
  89948. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89949. */
  89950. this.updateGizmoPositionToMatchAttachedMesh = true;
  89951. /**
  89952. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89953. */
  89954. this._updateScale = true;
  89955. this._interactionsEnabled = true;
  89956. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89957. var tempVector = new BABYLON.Vector3();
  89958. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89959. if (_this.attachedMesh) {
  89960. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89961. if (!_this._rootMesh.rotationQuaternion) {
  89962. _this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._rootMesh.rotation.y, _this._rootMesh.rotation.x, _this._rootMesh.rotation.z);
  89963. }
  89964. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  89965. tempVector.copyFrom(_this.attachedMesh.scaling);
  89966. if (_this.attachedMesh.scaling.x < 0) {
  89967. _this.attachedMesh.scaling.x *= -1;
  89968. }
  89969. if (_this.attachedMesh.scaling.y < 0) {
  89970. _this.attachedMesh.scaling.y *= -1;
  89971. }
  89972. if (_this.attachedMesh.scaling.z < 0) {
  89973. _this.attachedMesh.scaling.z *= -1;
  89974. }
  89975. _this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89976. _this.attachedMesh.scaling.copyFrom(tempVector);
  89977. _this.attachedMesh.computeWorldMatrix();
  89978. BABYLON.Quaternion.FromRotationMatrixToRef(_this._tmpMatrix, _this._rootMesh.rotationQuaternion);
  89979. }
  89980. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89981. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89982. }
  89983. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89984. var cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.position;
  89985. if (_this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  89986. cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  89987. }
  89988. _this._rootMesh.position.subtractToRef(cameraPosition, tempVector);
  89989. var dist = tempVector.length() / _this._scaleFactor;
  89990. _this._rootMesh.scaling.set(dist, dist, dist);
  89991. }
  89992. }
  89993. });
  89994. this.attachedMesh = null;
  89995. }
  89996. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89997. /**
  89998. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89999. * * When set, interactions will be enabled
  90000. */
  90001. get: function () {
  90002. return this._attachedMesh;
  90003. },
  90004. set: function (value) {
  90005. this._attachedMesh = value;
  90006. this._rootMesh.setEnabled(value ? true : false);
  90007. this._attachedMeshChanged(value);
  90008. },
  90009. enumerable: true,
  90010. configurable: true
  90011. });
  90012. /**
  90013. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  90014. * @param mesh The mesh to replace the default mesh of the gizmo
  90015. */
  90016. Gizmo.prototype.setCustomMesh = function (mesh) {
  90017. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  90018. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  90019. }
  90020. this._rootMesh.getChildMeshes().forEach(function (c) {
  90021. c.dispose();
  90022. });
  90023. mesh.parent = this._rootMesh;
  90024. this._customMeshSet = true;
  90025. };
  90026. Gizmo.prototype._attachedMeshChanged = function (value) {
  90027. };
  90028. /**
  90029. * Disposes of the gizmo
  90030. */
  90031. Gizmo.prototype.dispose = function () {
  90032. this._rootMesh.dispose();
  90033. if (this._beforeRenderObserver) {
  90034. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  90035. }
  90036. };
  90037. return Gizmo;
  90038. }());
  90039. BABYLON.Gizmo = Gizmo;
  90040. })(BABYLON || (BABYLON = {}));
  90041. //# sourceMappingURL=babylon.gizmo.js.map
  90042. var BABYLON;
  90043. (function (BABYLON) {
  90044. /**
  90045. * Single axis drag gizmo
  90046. */
  90047. var AxisDragGizmo = /** @class */ (function (_super) {
  90048. __extends(AxisDragGizmo, _super);
  90049. /**
  90050. * Creates an AxisDragGizmo
  90051. * @param gizmoLayer The utility layer the gizmo will be added to
  90052. * @param dragAxis The axis which the gizmo will be able to drag on
  90053. * @param color The color of the gizmo
  90054. */
  90055. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  90056. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90057. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90058. var _this = _super.call(this, gizmoLayer) || this;
  90059. _this._pointerObserver = null;
  90060. /**
  90061. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90062. */
  90063. _this.snapDistance = 0;
  90064. /**
  90065. * Event that fires each time the gizmo snaps to a new location.
  90066. * * snapDistance is the the change in distance
  90067. */
  90068. _this.onSnapObservable = new BABYLON.Observable();
  90069. // Create Material
  90070. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90071. coloredMaterial.disableLighting = true;
  90072. coloredMaterial.emissiveColor = color;
  90073. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90074. hoverMaterial.disableLighting = true;
  90075. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90076. // Build mesh on root node
  90077. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90078. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90079. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90080. arrow.addChild(arrowMesh);
  90081. arrow.addChild(arrowTail);
  90082. // Position arrow pointing in its drag axis
  90083. arrowMesh.scaling.scaleInPlace(0.05);
  90084. arrowMesh.material = coloredMaterial;
  90085. arrowMesh.rotation.x = Math.PI / 2;
  90086. arrowMesh.position.z += 0.3;
  90087. arrowTail.rotation.x = Math.PI / 2;
  90088. arrowTail.material = coloredMaterial;
  90089. arrowTail.position.z += 0.15;
  90090. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90091. _this._rootMesh.addChild(arrow);
  90092. var currentSnapDragDistance = 0;
  90093. var tmpVector = new BABYLON.Vector3();
  90094. var tmpSnapEvent = { snapDistance: 0 };
  90095. // Add drag behavior to handle events when the gizmo is dragged
  90096. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90097. _this.dragBehavior.moveAttached = false;
  90098. _this._rootMesh.addBehavior(_this.dragBehavior);
  90099. _this.dragBehavior.onDragObservable.add(function (event) {
  90100. if (_this.attachedMesh) {
  90101. // Snapping logic
  90102. if (_this.snapDistance == 0) {
  90103. _this.attachedMesh.position.addInPlace(event.delta);
  90104. }
  90105. else {
  90106. currentSnapDragDistance += event.dragDistance;
  90107. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90108. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  90109. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90110. event.delta.normalizeToRef(tmpVector);
  90111. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  90112. _this.attachedMesh.position.addInPlace(tmpVector);
  90113. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90114. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90115. }
  90116. }
  90117. }
  90118. });
  90119. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90120. if (_this._customMeshSet) {
  90121. return;
  90122. }
  90123. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  90124. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90125. m.material = hoverMaterial;
  90126. });
  90127. }
  90128. else {
  90129. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90130. m.material = coloredMaterial;
  90131. });
  90132. }
  90133. });
  90134. return _this;
  90135. }
  90136. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  90137. if (this.dragBehavior) {
  90138. this.dragBehavior.enabled = value ? true : false;
  90139. }
  90140. };
  90141. /**
  90142. * Disposes of the gizmo
  90143. */
  90144. AxisDragGizmo.prototype.dispose = function () {
  90145. this.onSnapObservable.clear();
  90146. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90147. this.dragBehavior.detach();
  90148. _super.prototype.dispose.call(this);
  90149. };
  90150. return AxisDragGizmo;
  90151. }(BABYLON.Gizmo));
  90152. BABYLON.AxisDragGizmo = AxisDragGizmo;
  90153. })(BABYLON || (BABYLON = {}));
  90154. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  90155. var BABYLON;
  90156. (function (BABYLON) {
  90157. /**
  90158. * Single axis scale gizmo
  90159. */
  90160. var AxisScaleGizmo = /** @class */ (function (_super) {
  90161. __extends(AxisScaleGizmo, _super);
  90162. /**
  90163. * Creates an AxisScaleGizmo
  90164. * @param gizmoLayer The utility layer the gizmo will be added to
  90165. * @param dragAxis The axis which the gizmo will be able to scale on
  90166. * @param color The color of the gizmo
  90167. */
  90168. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  90169. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90170. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90171. var _this = _super.call(this, gizmoLayer) || this;
  90172. _this._pointerObserver = null;
  90173. /**
  90174. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90175. */
  90176. _this.snapDistance = 0;
  90177. /**
  90178. * Event that fires each time the gizmo snaps to a new location.
  90179. * * snapDistance is the the change in distance
  90180. */
  90181. _this.onSnapObservable = new BABYLON.Observable();
  90182. // Create Material
  90183. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90184. coloredMaterial.disableLighting = true;
  90185. coloredMaterial.emissiveColor = color;
  90186. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90187. hoverMaterial.disableLighting = true;
  90188. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90189. // Build mesh on root node
  90190. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90191. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  90192. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90193. arrow.addChild(arrowMesh);
  90194. arrow.addChild(arrowTail);
  90195. // Position arrow pointing in its drag axis
  90196. arrowMesh.scaling.scaleInPlace(0.1);
  90197. arrowMesh.material = coloredMaterial;
  90198. arrowMesh.rotation.x = Math.PI / 2;
  90199. arrowMesh.position.z += 0.3;
  90200. arrowTail.rotation.x = Math.PI / 2;
  90201. arrowTail.material = coloredMaterial;
  90202. arrowTail.position.z += 0.15;
  90203. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90204. _this._rootMesh.addChild(arrow);
  90205. // Add drag behavior to handle events when the gizmo is dragged
  90206. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90207. _this.dragBehavior.moveAttached = false;
  90208. _this._rootMesh.addBehavior(_this.dragBehavior);
  90209. var currentSnapDragDistance = 0;
  90210. var tmpVector = new BABYLON.Vector3();
  90211. var tmpSnapEvent = { snapDistance: 0 };
  90212. _this.dragBehavior.onDragObservable.add(function (event) {
  90213. if (_this.attachedMesh) {
  90214. // Snapping logic
  90215. var snapped = false;
  90216. var dragSteps = 0;
  90217. if (_this.snapDistance == 0) {
  90218. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  90219. }
  90220. else {
  90221. currentSnapDragDistance += event.dragDistance;
  90222. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90223. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90224. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90225. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  90226. snapped = true;
  90227. }
  90228. else {
  90229. tmpVector.scaleInPlace(0);
  90230. }
  90231. }
  90232. _this.attachedMesh.scaling.addInPlace(tmpVector);
  90233. if (snapped) {
  90234. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90235. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90236. }
  90237. }
  90238. });
  90239. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90240. if (_this._customMeshSet) {
  90241. return;
  90242. }
  90243. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  90244. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90245. m.material = hoverMaterial;
  90246. });
  90247. }
  90248. else {
  90249. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90250. m.material = coloredMaterial;
  90251. });
  90252. }
  90253. });
  90254. return _this;
  90255. }
  90256. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  90257. if (this.dragBehavior) {
  90258. this.dragBehavior.enabled = value ? true : false;
  90259. }
  90260. };
  90261. /**
  90262. * Disposes of the gizmo
  90263. */
  90264. AxisScaleGizmo.prototype.dispose = function () {
  90265. this.onSnapObservable.clear();
  90266. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90267. this.dragBehavior.detach();
  90268. _super.prototype.dispose.call(this);
  90269. };
  90270. return AxisScaleGizmo;
  90271. }(BABYLON.Gizmo));
  90272. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  90273. })(BABYLON || (BABYLON = {}));
  90274. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  90275. var BABYLON;
  90276. (function (BABYLON) {
  90277. /**
  90278. * Single plane rotation gizmo
  90279. */
  90280. var PlaneRotationGizmo = /** @class */ (function (_super) {
  90281. __extends(PlaneRotationGizmo, _super);
  90282. /**
  90283. * Creates a PlaneRotationGizmo
  90284. * @param gizmoLayer The utility layer the gizmo will be added to
  90285. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  90286. * @param color The color of the gizmo
  90287. */
  90288. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  90289. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90290. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90291. var _this = _super.call(this, gizmoLayer) || this;
  90292. _this._pointerObserver = null;
  90293. /**
  90294. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  90295. */
  90296. _this.snapDistance = 0;
  90297. /**
  90298. * Event that fires each time the gizmo snaps to a new location.
  90299. * * snapDistance is the the change in distance
  90300. */
  90301. _this.onSnapObservable = new BABYLON.Observable();
  90302. // Create Material
  90303. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90304. coloredMaterial.disableLighting = true;
  90305. coloredMaterial.emissiveColor = color;
  90306. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90307. hoverMaterial.disableLighting = true;
  90308. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90309. // Build mesh on root node
  90310. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90311. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  90312. // Position arrow pointing in its drag axis
  90313. rotationMesh.scaling.scaleInPlace(0.1);
  90314. rotationMesh.material = coloredMaterial;
  90315. rotationMesh.rotation.x = Math.PI / 2;
  90316. parentMesh.addChild(rotationMesh);
  90317. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  90318. _this._rootMesh.addChild(parentMesh);
  90319. // Add drag behavior to handle events when the gizmo is dragged
  90320. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  90321. _this.dragBehavior.moveAttached = false;
  90322. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  90323. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  90324. _this._rootMesh.addBehavior(_this.dragBehavior);
  90325. var lastDragPosition = new BABYLON.Vector3();
  90326. _this.dragBehavior.onDragStartObservable.add(function (e) {
  90327. if (_this.attachedMesh) {
  90328. lastDragPosition.copyFrom(e.dragPlanePoint);
  90329. }
  90330. });
  90331. var rotationMatrix = new BABYLON.Matrix();
  90332. var planeNormalTowardsCamera = new BABYLON.Vector3();
  90333. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  90334. var tmpSnapEvent = { snapDistance: 0 };
  90335. var currentSnapDragDistance = 0;
  90336. _this.dragBehavior.onDragObservable.add(function (event) {
  90337. if (_this.attachedMesh) {
  90338. if (!_this.attachedMesh.rotationQuaternion) {
  90339. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90340. }
  90341. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  90342. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  90343. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  90344. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  90345. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  90346. var angle = Math.atan2(cross.length(), dot);
  90347. planeNormalTowardsCamera.copyFrom(planeNormal);
  90348. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  90349. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90350. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  90351. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  90352. }
  90353. // Flip up vector depending on which side the camera is on
  90354. if (gizmoLayer.utilityLayerScene.activeCamera) {
  90355. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  90356. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  90357. planeNormalTowardsCamera.scaleInPlace(-1);
  90358. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  90359. }
  90360. }
  90361. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  90362. if (halfCircleSide)
  90363. angle = -angle;
  90364. // Snapping logic
  90365. var snapped = false;
  90366. if (_this.snapDistance != 0) {
  90367. currentSnapDragDistance += angle;
  90368. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90369. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90370. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90371. angle = _this.snapDistance * dragSteps;
  90372. snapped = true;
  90373. }
  90374. else {
  90375. angle = 0;
  90376. }
  90377. }
  90378. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  90379. var quaternionCoefficient = Math.sin(angle / 2);
  90380. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  90381. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90382. // Rotate selected mesh quaternion over fixed axis
  90383. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  90384. }
  90385. else {
  90386. // Rotate selected mesh quaternion over rotated axis
  90387. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  90388. }
  90389. lastDragPosition.copyFrom(event.dragPlanePoint);
  90390. if (snapped) {
  90391. tmpSnapEvent.snapDistance = angle;
  90392. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90393. }
  90394. }
  90395. });
  90396. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90397. if (_this._customMeshSet) {
  90398. return;
  90399. }
  90400. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  90401. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90402. m.material = hoverMaterial;
  90403. });
  90404. }
  90405. else {
  90406. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90407. m.material = coloredMaterial;
  90408. });
  90409. }
  90410. });
  90411. return _this;
  90412. }
  90413. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  90414. if (this.dragBehavior) {
  90415. this.dragBehavior.enabled = value ? true : false;
  90416. }
  90417. };
  90418. /**
  90419. * Disposes of the gizmo
  90420. */
  90421. PlaneRotationGizmo.prototype.dispose = function () {
  90422. this.onSnapObservable.clear();
  90423. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90424. this.dragBehavior.detach();
  90425. _super.prototype.dispose.call(this);
  90426. };
  90427. return PlaneRotationGizmo;
  90428. }(BABYLON.Gizmo));
  90429. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  90430. })(BABYLON || (BABYLON = {}));
  90431. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  90432. var BABYLON;
  90433. (function (BABYLON) {
  90434. /**
  90435. * Gizmo that enables dragging a mesh along 3 axis
  90436. */
  90437. var PositionGizmo = /** @class */ (function (_super) {
  90438. __extends(PositionGizmo, _super);
  90439. /**
  90440. * Creates a PositionGizmo
  90441. * @param gizmoLayer The utility layer the gizmo will be added to
  90442. */
  90443. function PositionGizmo(gizmoLayer) {
  90444. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90445. var _this = _super.call(this, gizmoLayer) || this;
  90446. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90447. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90448. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90449. _this.attachedMesh = null;
  90450. return _this;
  90451. }
  90452. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  90453. set: function (mesh) {
  90454. if (this.xGizmo) {
  90455. this.xGizmo.attachedMesh = mesh;
  90456. this.yGizmo.attachedMesh = mesh;
  90457. this.zGizmo.attachedMesh = mesh;
  90458. }
  90459. },
  90460. enumerable: true,
  90461. configurable: true
  90462. });
  90463. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90464. get: function () {
  90465. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90466. },
  90467. set: function (value) {
  90468. if (this.xGizmo) {
  90469. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90470. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90471. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90472. }
  90473. },
  90474. enumerable: true,
  90475. configurable: true
  90476. });
  90477. /**
  90478. * Disposes of the gizmo
  90479. */
  90480. PositionGizmo.prototype.dispose = function () {
  90481. this.xGizmo.dispose();
  90482. this.yGizmo.dispose();
  90483. this.zGizmo.dispose();
  90484. };
  90485. /**
  90486. * CustomMeshes are not supported by this gizmo
  90487. * @param mesh The mesh to replace the default mesh of the gizmo
  90488. */
  90489. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  90490. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  90491. };
  90492. return PositionGizmo;
  90493. }(BABYLON.Gizmo));
  90494. BABYLON.PositionGizmo = PositionGizmo;
  90495. })(BABYLON || (BABYLON = {}));
  90496. //# sourceMappingURL=babylon.positionGizmo.js.map
  90497. var BABYLON;
  90498. (function (BABYLON) {
  90499. /**
  90500. * Gizmo that enables rotating a mesh along 3 axis
  90501. */
  90502. var RotationGizmo = /** @class */ (function (_super) {
  90503. __extends(RotationGizmo, _super);
  90504. /**
  90505. * Creates a RotationGizmo
  90506. * @param gizmoLayer The utility layer the gizmo will be added to
  90507. */
  90508. function RotationGizmo(gizmoLayer) {
  90509. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90510. var _this = _super.call(this, gizmoLayer) || this;
  90511. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90512. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90513. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90514. _this.attachedMesh = null;
  90515. return _this;
  90516. }
  90517. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  90518. set: function (mesh) {
  90519. if (this.xGizmo) {
  90520. this.xGizmo.attachedMesh = mesh;
  90521. this.yGizmo.attachedMesh = mesh;
  90522. this.zGizmo.attachedMesh = mesh;
  90523. }
  90524. },
  90525. enumerable: true,
  90526. configurable: true
  90527. });
  90528. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90529. get: function () {
  90530. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90531. },
  90532. set: function (value) {
  90533. if (this.xGizmo) {
  90534. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90535. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90536. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90537. }
  90538. },
  90539. enumerable: true,
  90540. configurable: true
  90541. });
  90542. /**
  90543. * Disposes of the gizmo
  90544. */
  90545. RotationGizmo.prototype.dispose = function () {
  90546. this.xGizmo.dispose();
  90547. this.yGizmo.dispose();
  90548. this.zGizmo.dispose();
  90549. };
  90550. /**
  90551. * CustomMeshes are not supported by this gizmo
  90552. * @param mesh The mesh to replace the default mesh of the gizmo
  90553. */
  90554. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  90555. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  90556. };
  90557. return RotationGizmo;
  90558. }(BABYLON.Gizmo));
  90559. BABYLON.RotationGizmo = RotationGizmo;
  90560. })(BABYLON || (BABYLON = {}));
  90561. //# sourceMappingURL=babylon.rotationGizmo.js.map
  90562. var BABYLON;
  90563. (function (BABYLON) {
  90564. /**
  90565. * Gizmo that enables scaling a mesh along 3 axis
  90566. */
  90567. var ScaleGizmo = /** @class */ (function (_super) {
  90568. __extends(ScaleGizmo, _super);
  90569. /**
  90570. * Creates a ScaleGizmo
  90571. * @param gizmoLayer The utility layer the gizmo will be added to
  90572. */
  90573. function ScaleGizmo(gizmoLayer) {
  90574. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90575. var _this = _super.call(this, gizmoLayer) || this;
  90576. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90577. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90578. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90579. _this.attachedMesh = null;
  90580. return _this;
  90581. }
  90582. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  90583. set: function (mesh) {
  90584. if (this.xGizmo) {
  90585. this.xGizmo.attachedMesh = mesh;
  90586. this.yGizmo.attachedMesh = mesh;
  90587. this.zGizmo.attachedMesh = mesh;
  90588. }
  90589. },
  90590. enumerable: true,
  90591. configurable: true
  90592. });
  90593. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90594. get: function () {
  90595. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90596. },
  90597. set: function (value) {
  90598. if (this.xGizmo) {
  90599. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90600. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90601. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90602. }
  90603. },
  90604. enumerable: true,
  90605. configurable: true
  90606. });
  90607. /**
  90608. * Disposes of the gizmo
  90609. */
  90610. ScaleGizmo.prototype.dispose = function () {
  90611. this.xGizmo.dispose();
  90612. this.yGizmo.dispose();
  90613. this.zGizmo.dispose();
  90614. };
  90615. return ScaleGizmo;
  90616. }(BABYLON.Gizmo));
  90617. BABYLON.ScaleGizmo = ScaleGizmo;
  90618. })(BABYLON || (BABYLON = {}));
  90619. //# sourceMappingURL=babylon.scaleGizmo.js.map
  90620. var BABYLON;
  90621. (function (BABYLON) {
  90622. /**
  90623. * Bounding box gizmo
  90624. */
  90625. var BoundingBoxGizmo = /** @class */ (function (_super) {
  90626. __extends(BoundingBoxGizmo, _super);
  90627. /**
  90628. * Creates an BoundingBoxGizmo
  90629. * @param gizmoLayer The utility layer the gizmo will be added to
  90630. * @param color The color of the gizmo
  90631. */
  90632. function BoundingBoxGizmo(color, gizmoLayer) {
  90633. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90634. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  90635. var _this = _super.call(this, gizmoLayer) || this;
  90636. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  90637. _this._renderObserver = null;
  90638. _this._pointerObserver = null;
  90639. _this._scaleDragSpeed = 0.2;
  90640. _this._tmpQuaternion = new BABYLON.Quaternion();
  90641. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90642. /**
  90643. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  90644. */
  90645. _this.rotationSphereSize = 0.1;
  90646. /**
  90647. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  90648. */
  90649. _this.scaleBoxSize = 0.1;
  90650. /**
  90651. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  90652. */
  90653. _this.fixedDragMeshScreenSize = false;
  90654. /**
  90655. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  90656. */
  90657. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  90658. /**
  90659. * Fired when a rotation sphere or scale box is dragged
  90660. */
  90661. _this.onDragStartObservable = new BABYLON.Observable();
  90662. /**
  90663. * Fired when a rotation sphere or scale box drag is started
  90664. */
  90665. _this.onDragObservable = new BABYLON.Observable();
  90666. /**
  90667. * Fired when a rotation sphere or scale box drag is needed
  90668. */
  90669. _this.onDragEndObservable = new BABYLON.Observable();
  90670. _this._existingMeshScale = new BABYLON.Vector3();
  90671. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  90672. _this._updateScale = false;
  90673. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  90674. // Create Materials
  90675. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90676. coloredMaterial.disableLighting = true;
  90677. coloredMaterial.emissiveColor = color;
  90678. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90679. hoverColoredMaterial.disableLighting = true;
  90680. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90681. // Build bounding box out of lines
  90682. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90683. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  90684. var lines = [];
  90685. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  90686. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90687. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90688. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90689. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90690. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90691. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90692. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90693. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90694. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90695. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90696. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90697. lines.forEach(function (l) {
  90698. l.color = color;
  90699. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90700. l.isPickable = false;
  90701. _this._lineBoundingBox.addChild(l);
  90702. });
  90703. _this._rootMesh.addChild(_this._lineBoundingBox);
  90704. // Create rotation spheres
  90705. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90706. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90707. var _loop_1 = function (i_1) {
  90708. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90709. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90710. sphere.material = coloredMaterial;
  90711. // Drag behavior
  90712. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90713. _dragBehavior.moveAttached = false;
  90714. _dragBehavior.updateDragPlane = false;
  90715. sphere.addBehavior(_dragBehavior);
  90716. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90717. var totalTurnAmountOfDrag = 0;
  90718. _dragBehavior.onDragStartObservable.add(function (event) {
  90719. startingTurnDirection.copyFrom(sphere.forward);
  90720. totalTurnAmountOfDrag = 0;
  90721. });
  90722. _dragBehavior.onDragObservable.add(function (event) {
  90723. _this.onDragObservable.notifyObservers({});
  90724. if (_this.attachedMesh) {
  90725. var worldDragDirection = startingTurnDirection;
  90726. // Project the world right on to the drag plane
  90727. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90728. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90729. // project drag delta on to the resulting drag axis and rotate based on that
  90730. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90731. // Rotate based on axis
  90732. if (!_this.attachedMesh.rotationQuaternion) {
  90733. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90734. }
  90735. if (!_this._anchorMesh.rotationQuaternion) {
  90736. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  90737. }
  90738. // Do not allow the object to turn more than a full circle
  90739. totalTurnAmountOfDrag += projectDist;
  90740. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90741. if (i_1 >= 8) {
  90742. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90743. }
  90744. else if (i_1 >= 4) {
  90745. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90746. }
  90747. else {
  90748. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90749. }
  90750. // Rotate around center of bounding box
  90751. _this._anchorMesh.addChild(_this.attachedMesh);
  90752. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  90753. _this._anchorMesh.removeChild(_this.attachedMesh);
  90754. }
  90755. _this.updateBoundingBox();
  90756. }
  90757. });
  90758. // Selection/deselection
  90759. _dragBehavior.onDragStartObservable.add(function () {
  90760. _this.onDragStartObservable.notifyObservers({});
  90761. _this._selectNode(sphere);
  90762. });
  90763. _dragBehavior.onDragEndObservable.add(function () {
  90764. _this.onDragEndObservable.notifyObservers({});
  90765. _this._selectNode(null);
  90766. });
  90767. this_1._rotateSpheresParent.addChild(sphere);
  90768. };
  90769. var this_1 = this, _dragBehavior;
  90770. for (var i_1 = 0; i_1 < 12; i_1++) {
  90771. _loop_1(i_1);
  90772. }
  90773. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90774. // Create scale cubes
  90775. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90776. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90777. for (var i = 0; i < 2; i++) {
  90778. for (var j = 0; j < 2; j++) {
  90779. var _loop_2 = function () {
  90780. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90781. box.material = coloredMaterial;
  90782. // Dragging logic
  90783. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90784. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90785. _dragBehavior.moveAttached = false;
  90786. box.addBehavior(_dragBehavior);
  90787. _dragBehavior.onDragObservable.add(function (event) {
  90788. _this.onDragObservable.notifyObservers({});
  90789. if (_this.attachedMesh) {
  90790. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  90791. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90792. _this.updateBoundingBox();
  90793. // Scale from the position of the opposite corner
  90794. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  90795. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  90796. _this._anchorMesh.addChild(_this.attachedMesh);
  90797. _this._anchorMesh.scaling.addInPlace(deltaScale);
  90798. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  90799. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  90800. }
  90801. _this._anchorMesh.removeChild(_this.attachedMesh);
  90802. }
  90803. });
  90804. // Selection/deselection
  90805. _dragBehavior.onDragStartObservable.add(function () {
  90806. _this.onDragStartObservable.notifyObservers({});
  90807. _this._selectNode(box);
  90808. });
  90809. _dragBehavior.onDragEndObservable.add(function () {
  90810. _this.onDragEndObservable.notifyObservers({});
  90811. _this._selectNode(null);
  90812. });
  90813. this_2._scaleBoxesParent.addChild(box);
  90814. };
  90815. var this_2 = this, _dragBehavior;
  90816. for (var k = 0; k < 2; k++) {
  90817. _loop_2();
  90818. }
  90819. }
  90820. }
  90821. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90822. // Hover color change
  90823. var pointerIds = new Array();
  90824. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90825. if (!pointerIds[pointerInfo.event.pointerId]) {
  90826. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90827. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90828. pointerIds[pointerInfo.event.pointerId] = mesh;
  90829. mesh.material = hoverColoredMaterial;
  90830. }
  90831. });
  90832. }
  90833. else {
  90834. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90835. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90836. delete pointerIds[pointerInfo.event.pointerId];
  90837. }
  90838. }
  90839. });
  90840. // Update bounding box positions
  90841. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90842. // Only update the bouding box if scaling has changed
  90843. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  90844. _this.updateBoundingBox();
  90845. }
  90846. });
  90847. _this.updateBoundingBox();
  90848. return _this;
  90849. }
  90850. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  90851. if (value) {
  90852. // Reset anchor mesh to match attached mesh's scale
  90853. // This is needed to avoid invalid box/sphere position on first drag
  90854. this._anchorMesh.addChild(value);
  90855. this._anchorMesh.removeChild(value);
  90856. this.updateBoundingBox();
  90857. }
  90858. };
  90859. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90860. this._rotateSpheresParent.getChildMeshes()
  90861. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90862. m.isVisible = (!selectedMesh || m == selectedMesh);
  90863. });
  90864. };
  90865. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  90866. var _this = this;
  90867. mesh.computeWorldMatrix(true);
  90868. mesh.getChildMeshes().forEach(function (m) {
  90869. _this._recurseComputeWorld(m);
  90870. });
  90871. };
  90872. /**
  90873. * Updates the bounding box information for the Gizmo
  90874. */
  90875. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  90876. if (this.attachedMesh) {
  90877. // Rotate based on axis
  90878. if (!this.attachedMesh.rotationQuaternion) {
  90879. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  90880. }
  90881. if (!this._anchorMesh.rotationQuaternion) {
  90882. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  90883. }
  90884. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90885. // Store original position and reset mesh to origin before computing the bounding box
  90886. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90887. this._tmpVector.copyFrom(this.attachedMesh.position);
  90888. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  90889. this.attachedMesh.position.set(0, 0, 0);
  90890. // Update bounding dimensions/positions
  90891. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();
  90892. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  90893. // Update gizmo to match bounding box scaling and rotation
  90894. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90895. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  90896. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  90897. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  90898. this._lineBoundingBox.computeWorldMatrix();
  90899. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  90900. // restore position/rotation values
  90901. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  90902. this.attachedMesh.position.copyFrom(this._tmpVector);
  90903. this._recurseComputeWorld(this.attachedMesh);
  90904. }
  90905. // Update rotation sphere locations
  90906. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90907. for (var i = 0; i < 3; i++) {
  90908. for (var j = 0; j < 2; j++) {
  90909. for (var k = 0; k < 2; k++) {
  90910. var index = ((i * 4) + (j * 2)) + k;
  90911. if (i == 0) {
  90912. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90913. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90914. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90915. }
  90916. if (i == 1) {
  90917. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90918. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90919. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90920. }
  90921. if (i == 2) {
  90922. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90923. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90924. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90925. }
  90926. if (this.fixedDragMeshScreenSize) {
  90927. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90928. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90929. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90930. }
  90931. else {
  90932. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  90933. }
  90934. }
  90935. }
  90936. }
  90937. // Update scale box locations
  90938. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  90939. for (var i = 0; i < 2; i++) {
  90940. for (var j = 0; j < 2; j++) {
  90941. for (var k = 0; k < 2; k++) {
  90942. var index = ((i * 4) + (j * 2)) + k;
  90943. if (scaleBoxes[index]) {
  90944. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90945. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90946. if (this.fixedDragMeshScreenSize) {
  90947. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90948. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90949. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90950. }
  90951. else {
  90952. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90953. }
  90954. }
  90955. }
  90956. }
  90957. }
  90958. if (this.attachedMesh) {
  90959. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  90960. }
  90961. };
  90962. /**
  90963. * Enables rotation on the specified axis and disables rotation on the others
  90964. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90965. */
  90966. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90967. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90968. if (i < 4) {
  90969. m.setEnabled(axis.indexOf("x") != -1);
  90970. }
  90971. else if (i < 8) {
  90972. m.setEnabled(axis.indexOf("y") != -1);
  90973. }
  90974. else {
  90975. m.setEnabled(axis.indexOf("z") != -1);
  90976. }
  90977. });
  90978. };
  90979. /**
  90980. * Disposes of the gizmo
  90981. */
  90982. BoundingBoxGizmo.prototype.dispose = function () {
  90983. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90984. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  90985. this._lineBoundingBox.dispose();
  90986. this._rotateSpheresParent.dispose();
  90987. this._scaleBoxesParent.dispose();
  90988. _super.prototype.dispose.call(this);
  90989. };
  90990. /**
  90991. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  90992. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  90993. * @returns the bounding box mesh with the passed in mesh as a child
  90994. */
  90995. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  90996. var makeNotPickable = function (root) {
  90997. root.isPickable = false;
  90998. root.getChildMeshes().forEach(function (c) {
  90999. makeNotPickable(c);
  91000. });
  91001. };
  91002. makeNotPickable(mesh);
  91003. // Reset position to get boudning box from origin with no rotation
  91004. if (!mesh.rotationQuaternion) {
  91005. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  91006. }
  91007. var oldPos = mesh.position.clone();
  91008. var oldRot = mesh.rotationQuaternion.clone();
  91009. mesh.rotationQuaternion.set(0, 0, 0, 1);
  91010. mesh.position.set(0, 0, 0);
  91011. // Update bounding dimensions/positions
  91012. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  91013. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  91014. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  91015. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  91016. // Restore original positions
  91017. mesh.addChild(box);
  91018. mesh.rotationQuaternion.copyFrom(oldRot);
  91019. mesh.position.copyFrom(oldPos);
  91020. // Reverse parenting
  91021. mesh.removeChild(box);
  91022. box.addChild(mesh);
  91023. box.visibility = 0;
  91024. return box;
  91025. };
  91026. /**
  91027. * CustomMeshes are not supported by this gizmo
  91028. * @param mesh The mesh to replace the default mesh of the gizmo
  91029. */
  91030. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  91031. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  91032. };
  91033. return BoundingBoxGizmo;
  91034. }(BABYLON.Gizmo));
  91035. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  91036. })(BABYLON || (BABYLON = {}));
  91037. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  91038. var BABYLON;
  91039. (function (BABYLON) {
  91040. /**
  91041. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  91042. */
  91043. var GizmoManager = /** @class */ (function () {
  91044. /**
  91045. * Instatiates a gizmo manager
  91046. * @param scene the scene to overlay the gizmos on top of
  91047. */
  91048. function GizmoManager(scene) {
  91049. var _this = this;
  91050. this.scene = scene;
  91051. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  91052. this._pointerObserver = null;
  91053. this._attachedMesh = null;
  91054. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  91055. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  91056. /**
  91057. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  91058. */
  91059. this.attachableMeshes = null;
  91060. /**
  91061. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  91062. */
  91063. this.usePointerToAttachGizmos = true;
  91064. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  91065. // Instatiate/dispose gizmos based on pointer actions
  91066. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  91067. if (!_this.usePointerToAttachGizmos) {
  91068. return;
  91069. }
  91070. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91071. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  91072. var node = pointerInfo.pickInfo.pickedMesh;
  91073. if (_this.attachableMeshes == null) {
  91074. // Attach to the most parent node
  91075. while (node && node.parent != null) {
  91076. node = node.parent;
  91077. }
  91078. }
  91079. else {
  91080. // Attach to the parent node that is an attachableMesh
  91081. var found = false;
  91082. _this.attachableMeshes.forEach(function (mesh) {
  91083. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  91084. node = mesh;
  91085. found = true;
  91086. }
  91087. });
  91088. if (!found) {
  91089. node = null;
  91090. }
  91091. }
  91092. if (node instanceof BABYLON.AbstractMesh) {
  91093. _this.attachToMesh(node);
  91094. }
  91095. }
  91096. else {
  91097. _this.attachToMesh(null);
  91098. }
  91099. }
  91100. });
  91101. }
  91102. /**
  91103. * Attaches a set of gizmos to the specified mesh
  91104. * @param mesh The mesh the gizmo's should be attached to
  91105. */
  91106. GizmoManager.prototype.attachToMesh = function (mesh) {
  91107. if (this._attachedMesh) {
  91108. this._attachedMesh.removeBehavior(this._dragBehavior);
  91109. }
  91110. this._attachedMesh = mesh;
  91111. for (var key in this.gizmos) {
  91112. var gizmo = (this.gizmos[key]);
  91113. if (gizmo && this._gizmosEnabled[key]) {
  91114. gizmo.attachedMesh = mesh;
  91115. }
  91116. }
  91117. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  91118. this._attachedMesh.addBehavior(this._dragBehavior);
  91119. }
  91120. };
  91121. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  91122. get: function () {
  91123. return this._gizmosEnabled.positionGizmo;
  91124. },
  91125. /**
  91126. * If the position gizmo is enabled
  91127. */
  91128. set: function (value) {
  91129. if (value) {
  91130. this.gizmos.positionGizmo = this.gizmos.positionGizmo || new BABYLON.PositionGizmo();
  91131. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91132. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  91133. }
  91134. else if (this.gizmos.positionGizmo) {
  91135. this.gizmos.positionGizmo.attachedMesh = null;
  91136. }
  91137. this._gizmosEnabled.positionGizmo = value;
  91138. },
  91139. enumerable: true,
  91140. configurable: true
  91141. });
  91142. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  91143. get: function () {
  91144. return this._gizmosEnabled.rotationGizmo;
  91145. },
  91146. /**
  91147. * If the rotation gizmo is enabled
  91148. */
  91149. set: function (value) {
  91150. if (value) {
  91151. this.gizmos.rotationGizmo = this.gizmos.rotationGizmo || new BABYLON.RotationGizmo();
  91152. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91153. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  91154. }
  91155. else if (this.gizmos.rotationGizmo) {
  91156. this.gizmos.rotationGizmo.attachedMesh = null;
  91157. }
  91158. this._gizmosEnabled.rotationGizmo = value;
  91159. },
  91160. enumerable: true,
  91161. configurable: true
  91162. });
  91163. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  91164. get: function () {
  91165. return this._gizmosEnabled.scaleGizmo;
  91166. },
  91167. /**
  91168. * If the scale gizmo is enabled
  91169. */
  91170. set: function (value) {
  91171. if (value) {
  91172. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  91173. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  91174. }
  91175. else if (this.gizmos.scaleGizmo) {
  91176. this.gizmos.scaleGizmo.attachedMesh = null;
  91177. }
  91178. this._gizmosEnabled.scaleGizmo = value;
  91179. },
  91180. enumerable: true,
  91181. configurable: true
  91182. });
  91183. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  91184. get: function () {
  91185. return this._gizmosEnabled.boundingBoxGizmo;
  91186. },
  91187. /**
  91188. * If the boundingBox gizmo is enabled
  91189. */
  91190. set: function (value) {
  91191. if (value) {
  91192. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  91193. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  91194. if (this._attachedMesh) {
  91195. this._attachedMesh.removeBehavior(this._dragBehavior);
  91196. this._attachedMesh.addBehavior(this._dragBehavior);
  91197. }
  91198. }
  91199. else if (this.gizmos.boundingBoxGizmo) {
  91200. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  91201. }
  91202. this._gizmosEnabled.boundingBoxGizmo = value;
  91203. },
  91204. enumerable: true,
  91205. configurable: true
  91206. });
  91207. /**
  91208. * Disposes of the gizmo manager
  91209. */
  91210. GizmoManager.prototype.dispose = function () {
  91211. this.scene.onPointerObservable.remove(this._pointerObserver);
  91212. for (var key in this.gizmos) {
  91213. var gizmo = (this.gizmos[key]);
  91214. if (gizmo) {
  91215. gizmo.dispose();
  91216. }
  91217. }
  91218. this._gizmoLayer.dispose();
  91219. };
  91220. return GizmoManager;
  91221. }());
  91222. BABYLON.GizmoManager = GizmoManager;
  91223. })(BABYLON || (BABYLON = {}));
  91224. //# sourceMappingURL=babylon.gizmoManager.js.map
  91225. var BABYLON;
  91226. (function (BABYLON) {
  91227. /**
  91228. * Defines a target to use with MorphTargetManager
  91229. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91230. */
  91231. var MorphTarget = /** @class */ (function () {
  91232. /**
  91233. * Creates a new MorphTarget
  91234. * @param name defines the name of the target
  91235. * @param influence defines the influence to use
  91236. */
  91237. function MorphTarget(
  91238. /** defines the name of the target */
  91239. name, influence, scene) {
  91240. if (influence === void 0) { influence = 0; }
  91241. if (scene === void 0) { scene = null; }
  91242. this.name = name;
  91243. /**
  91244. * Gets or sets the list of animations
  91245. */
  91246. this.animations = new Array();
  91247. this._positions = null;
  91248. this._normals = null;
  91249. this._tangents = null;
  91250. /**
  91251. * Observable raised when the influence changes
  91252. */
  91253. this.onInfluenceChanged = new BABYLON.Observable();
  91254. this._animationPropertiesOverride = null;
  91255. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91256. this.influence = influence;
  91257. }
  91258. Object.defineProperty(MorphTarget.prototype, "influence", {
  91259. /**
  91260. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  91261. */
  91262. get: function () {
  91263. return this._influence;
  91264. },
  91265. set: function (influence) {
  91266. if (this._influence === influence) {
  91267. return;
  91268. }
  91269. var previous = this._influence;
  91270. this._influence = influence;
  91271. if (this.onInfluenceChanged.hasObservers) {
  91272. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  91273. }
  91274. },
  91275. enumerable: true,
  91276. configurable: true
  91277. });
  91278. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  91279. /**
  91280. * Gets or sets the animation properties override
  91281. */
  91282. get: function () {
  91283. if (!this._animationPropertiesOverride && this._scene) {
  91284. return this._scene.animationPropertiesOverride;
  91285. }
  91286. return this._animationPropertiesOverride;
  91287. },
  91288. set: function (value) {
  91289. this._animationPropertiesOverride = value;
  91290. },
  91291. enumerable: true,
  91292. configurable: true
  91293. });
  91294. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  91295. /**
  91296. * Gets a boolean defining if the target contains position data
  91297. */
  91298. get: function () {
  91299. return !!this._positions;
  91300. },
  91301. enumerable: true,
  91302. configurable: true
  91303. });
  91304. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  91305. /**
  91306. * Gets a boolean defining if the target contains normal data
  91307. */
  91308. get: function () {
  91309. return !!this._normals;
  91310. },
  91311. enumerable: true,
  91312. configurable: true
  91313. });
  91314. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  91315. /**
  91316. * Gets a boolean defining if the target contains tangent data
  91317. */
  91318. get: function () {
  91319. return !!this._tangents;
  91320. },
  91321. enumerable: true,
  91322. configurable: true
  91323. });
  91324. /**
  91325. * Affects position data to this target
  91326. * @param data defines the position data to use
  91327. */
  91328. MorphTarget.prototype.setPositions = function (data) {
  91329. this._positions = data;
  91330. };
  91331. /**
  91332. * Gets the position data stored in this target
  91333. * @returns a FloatArray containing the position data (or null if not present)
  91334. */
  91335. MorphTarget.prototype.getPositions = function () {
  91336. return this._positions;
  91337. };
  91338. /**
  91339. * Affects normal data to this target
  91340. * @param data defines the normal data to use
  91341. */
  91342. MorphTarget.prototype.setNormals = function (data) {
  91343. this._normals = data;
  91344. };
  91345. /**
  91346. * Gets the normal data stored in this target
  91347. * @returns a FloatArray containing the normal data (or null if not present)
  91348. */
  91349. MorphTarget.prototype.getNormals = function () {
  91350. return this._normals;
  91351. };
  91352. /**
  91353. * Affects tangent data to this target
  91354. * @param data defines the tangent data to use
  91355. */
  91356. MorphTarget.prototype.setTangents = function (data) {
  91357. this._tangents = data;
  91358. };
  91359. /**
  91360. * Gets the tangent data stored in this target
  91361. * @returns a FloatArray containing the tangent data (or null if not present)
  91362. */
  91363. MorphTarget.prototype.getTangents = function () {
  91364. return this._tangents;
  91365. };
  91366. /**
  91367. * Serializes the current target into a Serialization object
  91368. * @returns the serialized object
  91369. */
  91370. MorphTarget.prototype.serialize = function () {
  91371. var serializationObject = {};
  91372. serializationObject.name = this.name;
  91373. serializationObject.influence = this.influence;
  91374. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  91375. if (this.hasNormals) {
  91376. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  91377. }
  91378. if (this.hasTangents) {
  91379. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  91380. }
  91381. // Animations
  91382. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  91383. return serializationObject;
  91384. };
  91385. // Statics
  91386. /**
  91387. * Creates a new target from serialized data
  91388. * @param serializationObject defines the serialized data to use
  91389. * @returns a new MorphTarget
  91390. */
  91391. MorphTarget.Parse = function (serializationObject) {
  91392. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  91393. result.setPositions(serializationObject.positions);
  91394. if (serializationObject.normals) {
  91395. result.setNormals(serializationObject.normals);
  91396. }
  91397. if (serializationObject.tangents) {
  91398. result.setTangents(serializationObject.tangents);
  91399. }
  91400. // Animations
  91401. if (serializationObject.animations) {
  91402. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  91403. var parsedAnimation = serializationObject.animations[animationIndex];
  91404. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  91405. }
  91406. }
  91407. return result;
  91408. };
  91409. /**
  91410. * Creates a MorphTarget from mesh data
  91411. * @param mesh defines the source mesh
  91412. * @param name defines the name to use for the new target
  91413. * @param influence defines the influence to attach to the target
  91414. * @returns a new MorphTarget
  91415. */
  91416. MorphTarget.FromMesh = function (mesh, name, influence) {
  91417. if (!name) {
  91418. name = mesh.name;
  91419. }
  91420. var result = new MorphTarget(name, influence, mesh.getScene());
  91421. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  91422. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91423. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  91424. }
  91425. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  91426. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  91427. }
  91428. return result;
  91429. };
  91430. return MorphTarget;
  91431. }());
  91432. BABYLON.MorphTarget = MorphTarget;
  91433. })(BABYLON || (BABYLON = {}));
  91434. //# sourceMappingURL=babylon.morphTarget.js.map
  91435. var BABYLON;
  91436. (function (BABYLON) {
  91437. /**
  91438. * This class is used to deform meshes using morphing between different targets
  91439. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91440. */
  91441. var MorphTargetManager = /** @class */ (function () {
  91442. /**
  91443. * Creates a new MorphTargetManager
  91444. * @param scene defines the current scene
  91445. */
  91446. function MorphTargetManager(scene) {
  91447. if (scene === void 0) { scene = null; }
  91448. this._targets = new Array();
  91449. this._targetObservable = new Array();
  91450. this._activeTargets = new BABYLON.SmartArray(16);
  91451. this._supportsNormals = false;
  91452. this._supportsTangents = false;
  91453. this._vertexCount = 0;
  91454. this._uniqueId = 0;
  91455. this._tempInfluences = new Array();
  91456. if (!scene) {
  91457. scene = BABYLON.Engine.LastCreatedScene;
  91458. }
  91459. this._scene = scene;
  91460. if (this._scene) {
  91461. this._scene.morphTargetManagers.push(this);
  91462. this._uniqueId = this._scene.getUniqueId();
  91463. }
  91464. }
  91465. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  91466. /**
  91467. * Gets the unique ID of this manager
  91468. */
  91469. get: function () {
  91470. return this._uniqueId;
  91471. },
  91472. enumerable: true,
  91473. configurable: true
  91474. });
  91475. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  91476. /**
  91477. * Gets the number of vertices handled by this manager
  91478. */
  91479. get: function () {
  91480. return this._vertexCount;
  91481. },
  91482. enumerable: true,
  91483. configurable: true
  91484. });
  91485. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  91486. /**
  91487. * Gets a boolean indicating if this manager supports morphing of normals
  91488. */
  91489. get: function () {
  91490. return this._supportsNormals;
  91491. },
  91492. enumerable: true,
  91493. configurable: true
  91494. });
  91495. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  91496. /**
  91497. * Gets a boolean indicating if this manager supports morphing of tangents
  91498. */
  91499. get: function () {
  91500. return this._supportsTangents;
  91501. },
  91502. enumerable: true,
  91503. configurable: true
  91504. });
  91505. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  91506. /**
  91507. * Gets the number of targets stored in this manager
  91508. */
  91509. get: function () {
  91510. return this._targets.length;
  91511. },
  91512. enumerable: true,
  91513. configurable: true
  91514. });
  91515. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  91516. /**
  91517. * Gets the number of influencers (ie. the number of targets with influences > 0)
  91518. */
  91519. get: function () {
  91520. return this._activeTargets.length;
  91521. },
  91522. enumerable: true,
  91523. configurable: true
  91524. });
  91525. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  91526. /**
  91527. * Gets the list of influences (one per target)
  91528. */
  91529. get: function () {
  91530. return this._influences;
  91531. },
  91532. enumerable: true,
  91533. configurable: true
  91534. });
  91535. /**
  91536. * Gets the active target at specified index. An active target is a target with an influence > 0
  91537. * @param index defines the index to check
  91538. * @returns the requested target
  91539. */
  91540. MorphTargetManager.prototype.getActiveTarget = function (index) {
  91541. return this._activeTargets.data[index];
  91542. };
  91543. /**
  91544. * Gets the target at specified index
  91545. * @param index defines the index to check
  91546. * @returns the requested target
  91547. */
  91548. MorphTargetManager.prototype.getTarget = function (index) {
  91549. return this._targets[index];
  91550. };
  91551. /**
  91552. * Add a new target to this manager
  91553. * @param target defines the target to add
  91554. */
  91555. MorphTargetManager.prototype.addTarget = function (target) {
  91556. var _this = this;
  91557. this._targets.push(target);
  91558. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  91559. _this._syncActiveTargets(needUpdate);
  91560. }));
  91561. this._syncActiveTargets(true);
  91562. };
  91563. /**
  91564. * Removes a target from the manager
  91565. * @param target defines the target to remove
  91566. */
  91567. MorphTargetManager.prototype.removeTarget = function (target) {
  91568. var index = this._targets.indexOf(target);
  91569. if (index >= 0) {
  91570. this._targets.splice(index, 1);
  91571. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  91572. this._syncActiveTargets(true);
  91573. }
  91574. };
  91575. /**
  91576. * Serializes the current manager into a Serialization object
  91577. * @returns the serialized object
  91578. */
  91579. MorphTargetManager.prototype.serialize = function () {
  91580. var serializationObject = {};
  91581. serializationObject.id = this.uniqueId;
  91582. serializationObject.targets = [];
  91583. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91584. var target = _a[_i];
  91585. serializationObject.targets.push(target.serialize());
  91586. }
  91587. return serializationObject;
  91588. };
  91589. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  91590. var influenceCount = 0;
  91591. this._activeTargets.reset();
  91592. this._supportsNormals = true;
  91593. this._supportsTangents = true;
  91594. this._vertexCount = 0;
  91595. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91596. var target = _a[_i];
  91597. this._activeTargets.push(target);
  91598. this._tempInfluences[influenceCount++] = target.influence;
  91599. var positions = target.getPositions();
  91600. if (positions) {
  91601. this._supportsNormals = this._supportsNormals && target.hasNormals;
  91602. this._supportsTangents = this._supportsTangents && target.hasTangents;
  91603. var vertexCount = positions.length / 3;
  91604. if (this._vertexCount === 0) {
  91605. this._vertexCount = vertexCount;
  91606. }
  91607. else if (this._vertexCount !== vertexCount) {
  91608. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  91609. return;
  91610. }
  91611. }
  91612. }
  91613. if (!this._influences || this._influences.length !== influenceCount) {
  91614. this._influences = new Float32Array(influenceCount);
  91615. }
  91616. for (var index = 0; index < influenceCount; index++) {
  91617. this._influences[index] = this._tempInfluences[index];
  91618. }
  91619. if (needUpdate) {
  91620. this.synchronize();
  91621. }
  91622. };
  91623. /**
  91624. * Syncrhonize the targets with all the meshes using this morph target manager
  91625. */
  91626. MorphTargetManager.prototype.synchronize = function () {
  91627. if (!this._scene) {
  91628. return;
  91629. }
  91630. // Flag meshes as dirty to resync with the active targets
  91631. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  91632. var mesh = _a[_i];
  91633. if (mesh.morphTargetManager === this) {
  91634. mesh._syncGeometryWithMorphTargetManager();
  91635. }
  91636. }
  91637. };
  91638. // Statics
  91639. /**
  91640. * Creates a new MorphTargetManager from serialized data
  91641. * @param serializationObject defines the serialized data
  91642. * @param scene defines the hosting scene
  91643. * @returns the new MorphTargetManager
  91644. */
  91645. MorphTargetManager.Parse = function (serializationObject, scene) {
  91646. var result = new MorphTargetManager(scene);
  91647. result._uniqueId = serializationObject.id;
  91648. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  91649. var targetData = _a[_i];
  91650. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  91651. }
  91652. return result;
  91653. };
  91654. return MorphTargetManager;
  91655. }());
  91656. BABYLON.MorphTargetManager = MorphTargetManager;
  91657. })(BABYLON || (BABYLON = {}));
  91658. //# sourceMappingURL=babylon.morphTargetManager.js.map
  91659. var BABYLON;
  91660. (function (BABYLON) {
  91661. var Octree = /** @class */ (function () {
  91662. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  91663. if (maxDepth === void 0) { maxDepth = 2; }
  91664. this.maxDepth = maxDepth;
  91665. this.dynamicContent = new Array();
  91666. this._maxBlockCapacity = maxBlockCapacity || 64;
  91667. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  91668. this._creationFunc = creationFunc;
  91669. }
  91670. // Methods
  91671. Octree.prototype.update = function (worldMin, worldMax, entries) {
  91672. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  91673. };
  91674. Octree.prototype.addMesh = function (entry) {
  91675. for (var index = 0; index < this.blocks.length; index++) {
  91676. var block = this.blocks[index];
  91677. block.addEntry(entry);
  91678. }
  91679. };
  91680. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  91681. this._selectionContent.reset();
  91682. for (var index = 0; index < this.blocks.length; index++) {
  91683. var block = this.blocks[index];
  91684. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  91685. }
  91686. if (allowDuplicate) {
  91687. this._selectionContent.concat(this.dynamicContent);
  91688. }
  91689. else {
  91690. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91691. }
  91692. return this._selectionContent;
  91693. };
  91694. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  91695. this._selectionContent.reset();
  91696. for (var index = 0; index < this.blocks.length; index++) {
  91697. var block = this.blocks[index];
  91698. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  91699. }
  91700. if (allowDuplicate) {
  91701. this._selectionContent.concat(this.dynamicContent);
  91702. }
  91703. else {
  91704. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91705. }
  91706. return this._selectionContent;
  91707. };
  91708. Octree.prototype.intersectsRay = function (ray) {
  91709. this._selectionContent.reset();
  91710. for (var index = 0; index < this.blocks.length; index++) {
  91711. var block = this.blocks[index];
  91712. block.intersectsRay(ray, this._selectionContent);
  91713. }
  91714. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91715. return this._selectionContent;
  91716. };
  91717. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  91718. target.blocks = new Array();
  91719. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  91720. // Segmenting space
  91721. for (var x = 0; x < 2; x++) {
  91722. for (var y = 0; y < 2; y++) {
  91723. for (var z = 0; z < 2; z++) {
  91724. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  91725. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  91726. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  91727. block.addEntries(entries);
  91728. target.blocks.push(block);
  91729. }
  91730. }
  91731. }
  91732. };
  91733. Octree.CreationFuncForMeshes = function (entry, block) {
  91734. var boundingInfo = entry.getBoundingInfo();
  91735. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91736. block.entries.push(entry);
  91737. }
  91738. };
  91739. Octree.CreationFuncForSubMeshes = function (entry, block) {
  91740. var boundingInfo = entry.getBoundingInfo();
  91741. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91742. block.entries.push(entry);
  91743. }
  91744. };
  91745. return Octree;
  91746. }());
  91747. BABYLON.Octree = Octree;
  91748. })(BABYLON || (BABYLON = {}));
  91749. //# sourceMappingURL=babylon.octree.js.map
  91750. var BABYLON;
  91751. (function (BABYLON) {
  91752. var OctreeBlock = /** @class */ (function () {
  91753. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  91754. this.entries = new Array();
  91755. this._boundingVectors = new Array();
  91756. this._capacity = capacity;
  91757. this._depth = depth;
  91758. this._maxDepth = maxDepth;
  91759. this._creationFunc = creationFunc;
  91760. this._minPoint = minPoint;
  91761. this._maxPoint = maxPoint;
  91762. this._boundingVectors.push(minPoint.clone());
  91763. this._boundingVectors.push(maxPoint.clone());
  91764. this._boundingVectors.push(minPoint.clone());
  91765. this._boundingVectors[2].x = maxPoint.x;
  91766. this._boundingVectors.push(minPoint.clone());
  91767. this._boundingVectors[3].y = maxPoint.y;
  91768. this._boundingVectors.push(minPoint.clone());
  91769. this._boundingVectors[4].z = maxPoint.z;
  91770. this._boundingVectors.push(maxPoint.clone());
  91771. this._boundingVectors[5].z = minPoint.z;
  91772. this._boundingVectors.push(maxPoint.clone());
  91773. this._boundingVectors[6].x = minPoint.x;
  91774. this._boundingVectors.push(maxPoint.clone());
  91775. this._boundingVectors[7].y = minPoint.y;
  91776. }
  91777. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  91778. // Property
  91779. get: function () {
  91780. return this._capacity;
  91781. },
  91782. enumerable: true,
  91783. configurable: true
  91784. });
  91785. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  91786. get: function () {
  91787. return this._minPoint;
  91788. },
  91789. enumerable: true,
  91790. configurable: true
  91791. });
  91792. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91793. get: function () {
  91794. return this._maxPoint;
  91795. },
  91796. enumerable: true,
  91797. configurable: true
  91798. });
  91799. // Methods
  91800. OctreeBlock.prototype.addEntry = function (entry) {
  91801. if (this.blocks) {
  91802. for (var index = 0; index < this.blocks.length; index++) {
  91803. var block = this.blocks[index];
  91804. block.addEntry(entry);
  91805. }
  91806. return;
  91807. }
  91808. this._creationFunc(entry, this);
  91809. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91810. this.createInnerBlocks();
  91811. }
  91812. };
  91813. OctreeBlock.prototype.addEntries = function (entries) {
  91814. for (var index = 0; index < entries.length; index++) {
  91815. var mesh = entries[index];
  91816. this.addEntry(mesh);
  91817. }
  91818. };
  91819. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91820. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91821. if (this.blocks) {
  91822. for (var index = 0; index < this.blocks.length; index++) {
  91823. var block = this.blocks[index];
  91824. block.select(frustumPlanes, selection, allowDuplicate);
  91825. }
  91826. return;
  91827. }
  91828. if (allowDuplicate) {
  91829. selection.concat(this.entries);
  91830. }
  91831. else {
  91832. selection.concatWithNoDuplicate(this.entries);
  91833. }
  91834. }
  91835. };
  91836. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91837. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  91838. if (this.blocks) {
  91839. for (var index = 0; index < this.blocks.length; index++) {
  91840. var block = this.blocks[index];
  91841. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  91842. }
  91843. return;
  91844. }
  91845. if (allowDuplicate) {
  91846. selection.concat(this.entries);
  91847. }
  91848. else {
  91849. selection.concatWithNoDuplicate(this.entries);
  91850. }
  91851. }
  91852. };
  91853. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  91854. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  91855. if (this.blocks) {
  91856. for (var index = 0; index < this.blocks.length; index++) {
  91857. var block = this.blocks[index];
  91858. block.intersectsRay(ray, selection);
  91859. }
  91860. return;
  91861. }
  91862. selection.concatWithNoDuplicate(this.entries);
  91863. }
  91864. };
  91865. OctreeBlock.prototype.createInnerBlocks = function () {
  91866. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  91867. };
  91868. return OctreeBlock;
  91869. }());
  91870. BABYLON.OctreeBlock = OctreeBlock;
  91871. })(BABYLON || (BABYLON = {}));
  91872. //# sourceMappingURL=babylon.octreeBlock.js.map
  91873. var BABYLON;
  91874. (function (BABYLON) {
  91875. /**
  91876. * Postprocess used to generate anaglyphic rendering
  91877. */
  91878. var AnaglyphPostProcess = /** @class */ (function (_super) {
  91879. __extends(AnaglyphPostProcess, _super);
  91880. /**
  91881. * Creates a new AnaglyphPostProcess
  91882. * @param name defines postprocess name
  91883. * @param options defines creation options or target ratio scale
  91884. * @param rigCameras defines cameras using this postprocess
  91885. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  91886. * @param engine defines hosting engine
  91887. * @param reusable defines if the postprocess will be reused multiple times per frame
  91888. */
  91889. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  91890. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  91891. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91892. _this.onApplyObservable.add(function (effect) {
  91893. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  91894. });
  91895. return _this;
  91896. }
  91897. return AnaglyphPostProcess;
  91898. }(BABYLON.PostProcess));
  91899. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  91900. })(BABYLON || (BABYLON = {}));
  91901. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  91902. var BABYLON;
  91903. (function (BABYLON) {
  91904. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  91905. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91906. });
  91907. /**
  91908. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91909. */
  91910. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91911. __extends(AnaglyphArcRotateCamera, _super);
  91912. /**
  91913. * Creates a new AnaglyphArcRotateCamera
  91914. * @param name defines camera name
  91915. * @param alpha defines alpha angle (in radians)
  91916. * @param beta defines beta angle (in radians)
  91917. * @param radius defines radius
  91918. * @param target defines camera target
  91919. * @param interaxialDistance defines distance between each color axis
  91920. * @param scene defines the hosting scene
  91921. */
  91922. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91923. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91924. _this.interaxialDistance = interaxialDistance;
  91925. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91926. return _this;
  91927. }
  91928. /**
  91929. * Gets camera class name
  91930. * @returns AnaglyphArcRotateCamera
  91931. */
  91932. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91933. return "AnaglyphArcRotateCamera";
  91934. };
  91935. return AnaglyphArcRotateCamera;
  91936. }(BABYLON.ArcRotateCamera));
  91937. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91938. })(BABYLON || (BABYLON = {}));
  91939. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  91940. var BABYLON;
  91941. (function (BABYLON) {
  91942. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  91943. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91944. });
  91945. /**
  91946. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91947. */
  91948. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91949. __extends(AnaglyphFreeCamera, _super);
  91950. /**
  91951. * Creates a new AnaglyphFreeCamera
  91952. * @param name defines camera name
  91953. * @param position defines initial position
  91954. * @param interaxialDistance defines distance between each color axis
  91955. * @param scene defines the hosting scene
  91956. */
  91957. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91958. var _this = _super.call(this, name, position, scene) || this;
  91959. _this.interaxialDistance = interaxialDistance;
  91960. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91961. return _this;
  91962. }
  91963. /**
  91964. * Gets camera class name
  91965. * @returns AnaglyphFreeCamera
  91966. */
  91967. AnaglyphFreeCamera.prototype.getClassName = function () {
  91968. return "AnaglyphFreeCamera";
  91969. };
  91970. return AnaglyphFreeCamera;
  91971. }(BABYLON.FreeCamera));
  91972. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91973. })(BABYLON || (BABYLON = {}));
  91974. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  91975. var BABYLON;
  91976. (function (BABYLON) {
  91977. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  91978. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91979. });
  91980. /**
  91981. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91982. */
  91983. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91984. __extends(AnaglyphGamepadCamera, _super);
  91985. /**
  91986. * Creates a new AnaglyphGamepadCamera
  91987. * @param name defines camera name
  91988. * @param position defines initial position
  91989. * @param interaxialDistance defines distance between each color axis
  91990. * @param scene defines the hosting scene
  91991. */
  91992. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91993. var _this = _super.call(this, name, position, scene) || this;
  91994. _this.interaxialDistance = interaxialDistance;
  91995. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91996. return _this;
  91997. }
  91998. /**
  91999. * Gets camera class name
  92000. * @returns AnaglyphGamepadCamera
  92001. */
  92002. AnaglyphGamepadCamera.prototype.getClassName = function () {
  92003. return "AnaglyphGamepadCamera";
  92004. };
  92005. return AnaglyphGamepadCamera;
  92006. }(BABYLON.GamepadCamera));
  92007. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  92008. })(BABYLON || (BABYLON = {}));
  92009. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  92010. var BABYLON;
  92011. (function (BABYLON) {
  92012. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  92013. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92014. });
  92015. /**
  92016. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  92017. */
  92018. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  92019. __extends(AnaglyphUniversalCamera, _super);
  92020. /**
  92021. * Creates a new AnaglyphUniversalCamera
  92022. * @param name defines camera name
  92023. * @param position defines initial position
  92024. * @param interaxialDistance defines distance between each color axis
  92025. * @param scene defines the hosting scene
  92026. */
  92027. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  92028. var _this = _super.call(this, name, position, scene) || this;
  92029. _this.interaxialDistance = interaxialDistance;
  92030. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92031. return _this;
  92032. }
  92033. /**
  92034. * Gets camera class name
  92035. * @returns AnaglyphUniversalCamera
  92036. */
  92037. AnaglyphUniversalCamera.prototype.getClassName = function () {
  92038. return "AnaglyphUniversalCamera";
  92039. };
  92040. return AnaglyphUniversalCamera;
  92041. }(BABYLON.UniversalCamera));
  92042. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  92043. })(BABYLON || (BABYLON = {}));
  92044. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  92045. var BABYLON;
  92046. (function (BABYLON) {
  92047. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  92048. __extends(StereoscopicInterlacePostProcess, _super);
  92049. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  92050. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  92051. _this._passedProcess = rigCameras[0]._rigPostProcess;
  92052. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92053. _this.onSizeChangedObservable.add(function () {
  92054. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92055. });
  92056. _this.onApplyObservable.add(function (effect) {
  92057. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  92058. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  92059. });
  92060. return _this;
  92061. }
  92062. return StereoscopicInterlacePostProcess;
  92063. }(BABYLON.PostProcess));
  92064. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  92065. })(BABYLON || (BABYLON = {}));
  92066. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  92067. var BABYLON;
  92068. (function (BABYLON) {
  92069. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  92070. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92071. });
  92072. /**
  92073. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  92074. */
  92075. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  92076. __extends(StereoscopicArcRotateCamera, _super);
  92077. /**
  92078. * Creates a new StereoscopicArcRotateCamera
  92079. * @param name defines camera name
  92080. * @param alpha defines alpha angle (in radians)
  92081. * @param beta defines beta angle (in radians)
  92082. * @param radius defines radius
  92083. * @param target defines camera target
  92084. * @param interaxialDistance defines distance between each color axis
  92085. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92086. * @param scene defines the hosting scene
  92087. */
  92088. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  92089. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92090. _this.interaxialDistance = interaxialDistance;
  92091. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92092. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92093. return _this;
  92094. }
  92095. /**
  92096. * Gets camera class name
  92097. * @returns StereoscopicArcRotateCamera
  92098. */
  92099. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  92100. return "StereoscopicArcRotateCamera";
  92101. };
  92102. return StereoscopicArcRotateCamera;
  92103. }(BABYLON.ArcRotateCamera));
  92104. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  92105. })(BABYLON || (BABYLON = {}));
  92106. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  92107. var BABYLON;
  92108. (function (BABYLON) {
  92109. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92110. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92111. });
  92112. /**
  92113. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  92114. */
  92115. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  92116. __extends(StereoscopicFreeCamera, _super);
  92117. /**
  92118. * Creates a new StereoscopicFreeCamera
  92119. * @param name defines camera name
  92120. * @param position defines initial position
  92121. * @param interaxialDistance defines distance between each color axis
  92122. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92123. * @param scene defines the hosting scene
  92124. */
  92125. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92126. var _this = _super.call(this, name, position, scene) || this;
  92127. _this.interaxialDistance = interaxialDistance;
  92128. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92129. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92130. return _this;
  92131. }
  92132. /**
  92133. * Gets camera class name
  92134. * @returns StereoscopicFreeCamera
  92135. */
  92136. StereoscopicFreeCamera.prototype.getClassName = function () {
  92137. return "StereoscopicFreeCamera";
  92138. };
  92139. return StereoscopicFreeCamera;
  92140. }(BABYLON.FreeCamera));
  92141. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  92142. })(BABYLON || (BABYLON = {}));
  92143. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  92144. var BABYLON;
  92145. (function (BABYLON) {
  92146. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  92147. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92148. });
  92149. /**
  92150. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  92151. */
  92152. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  92153. __extends(StereoscopicGamepadCamera, _super);
  92154. /**
  92155. * Creates a new StereoscopicGamepadCamera
  92156. * @param name defines camera name
  92157. * @param position defines initial position
  92158. * @param interaxialDistance defines distance between each color axis
  92159. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92160. * @param scene defines the hosting scene
  92161. */
  92162. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92163. var _this = _super.call(this, name, position, scene) || this;
  92164. _this.interaxialDistance = interaxialDistance;
  92165. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92166. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92167. return _this;
  92168. }
  92169. /**
  92170. * Gets camera class name
  92171. * @returns StereoscopicGamepadCamera
  92172. */
  92173. StereoscopicGamepadCamera.prototype.getClassName = function () {
  92174. return "StereoscopicGamepadCamera";
  92175. };
  92176. return StereoscopicGamepadCamera;
  92177. }(BABYLON.GamepadCamera));
  92178. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  92179. })(BABYLON || (BABYLON = {}));
  92180. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  92181. var BABYLON;
  92182. (function (BABYLON) {
  92183. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92184. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92185. });
  92186. /**
  92187. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  92188. */
  92189. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  92190. __extends(StereoscopicUniversalCamera, _super);
  92191. /**
  92192. * Creates a new StereoscopicUniversalCamera
  92193. * @param name defines camera name
  92194. * @param position defines initial position
  92195. * @param interaxialDistance defines distance between each color axis
  92196. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92197. * @param scene defines the hosting scene
  92198. */
  92199. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92200. var _this = _super.call(this, name, position, scene) || this;
  92201. _this.interaxialDistance = interaxialDistance;
  92202. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92203. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92204. return _this;
  92205. }
  92206. /**
  92207. * Gets camera class name
  92208. * @returns StereoscopicUniversalCamera
  92209. */
  92210. StereoscopicUniversalCamera.prototype.getClassName = function () {
  92211. return "StereoscopicUniversalCamera";
  92212. };
  92213. return StereoscopicUniversalCamera;
  92214. }(BABYLON.UniversalCamera));
  92215. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  92216. })(BABYLON || (BABYLON = {}));
  92217. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  92218. var BABYLON;
  92219. (function (BABYLON) {
  92220. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  92221. __extends(VRDistortionCorrectionPostProcess, _super);
  92222. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  92223. var _this = _super.call(this, name, "vrDistortionCorrection", [
  92224. 'LensCenter',
  92225. 'Scale',
  92226. 'ScaleIn',
  92227. 'HmdWarpParam'
  92228. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  92229. _this._isRightEye = isRightEye;
  92230. _this._distortionFactors = vrMetrics.distortionK;
  92231. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  92232. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  92233. _this.adaptScaleToCurrentViewport = true;
  92234. _this.onSizeChangedObservable.add(function () {
  92235. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  92236. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  92237. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  92238. });
  92239. _this.onApplyObservable.add(function (effect) {
  92240. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  92241. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  92242. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  92243. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  92244. });
  92245. return _this;
  92246. }
  92247. return VRDistortionCorrectionPostProcess;
  92248. }(BABYLON.PostProcess));
  92249. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  92250. })(BABYLON || (BABYLON = {}));
  92251. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  92252. var BABYLON;
  92253. (function (BABYLON) {
  92254. /**
  92255. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  92256. * Screen rotation is taken into account.
  92257. */
  92258. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  92259. function FreeCameraDeviceOrientationInput() {
  92260. var _this = this;
  92261. this._screenOrientationAngle = 0;
  92262. this._screenQuaternion = new BABYLON.Quaternion();
  92263. this._alpha = 0;
  92264. this._beta = 0;
  92265. this._gamma = 0;
  92266. this._orientationChanged = function () {
  92267. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  92268. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  92269. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  92270. };
  92271. this._deviceOrientation = function (evt) {
  92272. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  92273. _this._beta = evt.beta !== null ? evt.beta : 0;
  92274. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  92275. };
  92276. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  92277. this._orientationChanged();
  92278. }
  92279. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  92280. get: function () {
  92281. return this._camera;
  92282. },
  92283. set: function (camera) {
  92284. this._camera = camera;
  92285. if (this._camera != null && !this._camera.rotationQuaternion) {
  92286. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  92287. }
  92288. },
  92289. enumerable: true,
  92290. configurable: true
  92291. });
  92292. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92293. window.addEventListener("orientationchange", this._orientationChanged);
  92294. window.addEventListener("deviceorientation", this._deviceOrientation);
  92295. //In certain cases, the attach control is called AFTER orientation was changed,
  92296. //So this is needed.
  92297. this._orientationChanged();
  92298. };
  92299. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  92300. window.removeEventListener("orientationchange", this._orientationChanged);
  92301. window.removeEventListener("deviceorientation", this._deviceOrientation);
  92302. };
  92303. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  92304. //if no device orientation provided, don't update the rotation.
  92305. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  92306. if (!this._alpha)
  92307. return;
  92308. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  92309. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  92310. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  92311. //Mirror on XY Plane
  92312. this._camera.rotationQuaternion.z *= -1;
  92313. this._camera.rotationQuaternion.w *= -1;
  92314. };
  92315. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  92316. return "FreeCameraDeviceOrientationInput";
  92317. };
  92318. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  92319. return "deviceOrientation";
  92320. };
  92321. return FreeCameraDeviceOrientationInput;
  92322. }());
  92323. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  92324. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  92325. })(BABYLON || (BABYLON = {}));
  92326. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  92327. var BABYLON;
  92328. (function (BABYLON) {
  92329. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  92330. function ArcRotateCameraVRDeviceOrientationInput() {
  92331. this.alphaCorrection = 1;
  92332. this.betaCorrection = 1;
  92333. this.gammaCorrection = 1;
  92334. this._alpha = 0;
  92335. this._gamma = 0;
  92336. this._dirty = false;
  92337. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  92338. }
  92339. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92340. this.camera.attachControl(element, noPreventDefault);
  92341. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  92342. };
  92343. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  92344. if (evt.alpha !== null) {
  92345. this._alpha = +evt.alpha | 0;
  92346. }
  92347. if (evt.gamma !== null) {
  92348. this._gamma = +evt.gamma | 0;
  92349. }
  92350. this._dirty = true;
  92351. };
  92352. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  92353. if (this._dirty) {
  92354. this._dirty = false;
  92355. if (this._gamma < 0) {
  92356. this._gamma = 180 + this._gamma;
  92357. }
  92358. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  92359. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  92360. }
  92361. };
  92362. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  92363. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  92364. };
  92365. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  92366. return "ArcRotateCameraVRDeviceOrientationInput";
  92367. };
  92368. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  92369. return "VRDeviceOrientation";
  92370. };
  92371. return ArcRotateCameraVRDeviceOrientationInput;
  92372. }());
  92373. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  92374. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  92375. })(BABYLON || (BABYLON = {}));
  92376. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  92377. var BABYLON;
  92378. (function (BABYLON) {
  92379. var VRCameraMetrics = /** @class */ (function () {
  92380. function VRCameraMetrics() {
  92381. this.compensateDistortion = true;
  92382. }
  92383. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  92384. get: function () {
  92385. return this.hResolution / (2 * this.vResolution);
  92386. },
  92387. enumerable: true,
  92388. configurable: true
  92389. });
  92390. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  92391. get: function () {
  92392. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  92393. },
  92394. enumerable: true,
  92395. configurable: true
  92396. });
  92397. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  92398. get: function () {
  92399. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92400. var h = (4 * meters) / this.hScreenSize;
  92401. return BABYLON.Matrix.Translation(h, 0, 0);
  92402. },
  92403. enumerable: true,
  92404. configurable: true
  92405. });
  92406. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  92407. get: function () {
  92408. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92409. var h = (4 * meters) / this.hScreenSize;
  92410. return BABYLON.Matrix.Translation(-h, 0, 0);
  92411. },
  92412. enumerable: true,
  92413. configurable: true
  92414. });
  92415. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  92416. get: function () {
  92417. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  92418. },
  92419. enumerable: true,
  92420. configurable: true
  92421. });
  92422. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  92423. get: function () {
  92424. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  92425. },
  92426. enumerable: true,
  92427. configurable: true
  92428. });
  92429. VRCameraMetrics.GetDefault = function () {
  92430. var result = new VRCameraMetrics();
  92431. result.hResolution = 1280;
  92432. result.vResolution = 800;
  92433. result.hScreenSize = 0.149759993;
  92434. result.vScreenSize = 0.0935999975;
  92435. result.vScreenCenter = 0.0467999987;
  92436. result.eyeToScreenDistance = 0.0410000011;
  92437. result.lensSeparationDistance = 0.0635000020;
  92438. result.interpupillaryDistance = 0.0640000030;
  92439. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  92440. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  92441. result.postProcessScaleFactor = 1.714605507808412;
  92442. result.lensCenterOffset = 0.151976421;
  92443. return result;
  92444. };
  92445. return VRCameraMetrics;
  92446. }());
  92447. BABYLON.VRCameraMetrics = VRCameraMetrics;
  92448. })(BABYLON || (BABYLON = {}));
  92449. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  92450. var BABYLON;
  92451. (function (BABYLON) {
  92452. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  92453. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92454. });
  92455. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  92456. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92457. });
  92458. /**
  92459. * This represents a WebVR camera.
  92460. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  92461. * @example http://doc.babylonjs.com/how_to/webvr_camera
  92462. */
  92463. var WebVRFreeCamera = /** @class */ (function (_super) {
  92464. __extends(WebVRFreeCamera, _super);
  92465. /**
  92466. * Instantiates a WebVRFreeCamera.
  92467. * @param name The name of the WebVRFreeCamera
  92468. * @param position The starting anchor position for the camera
  92469. * @param scene The scene the camera belongs to
  92470. * @param webVROptions a set of customizable options for the webVRCamera
  92471. */
  92472. function WebVRFreeCamera(name, position, scene, webVROptions) {
  92473. if (webVROptions === void 0) { webVROptions = {}; }
  92474. var _this = _super.call(this, name, position, scene) || this;
  92475. _this.webVROptions = webVROptions;
  92476. /**
  92477. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  92478. */
  92479. _this._vrDevice = null;
  92480. /**
  92481. * The rawPose of the vrDevice.
  92482. */
  92483. _this.rawPose = null;
  92484. _this._specsVersion = "1.1";
  92485. _this._attached = false;
  92486. _this._descendants = [];
  92487. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  92488. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  92489. /** @hidden */
  92490. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  92491. _this._standingMatrix = null;
  92492. /**
  92493. * Represents device position in babylon space.
  92494. */
  92495. _this.devicePosition = BABYLON.Vector3.Zero();
  92496. /**
  92497. * Represents device rotation in babylon space.
  92498. */
  92499. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  92500. /**
  92501. * The scale of the device to be used when translating from device space to babylon space.
  92502. */
  92503. _this.deviceScaleFactor = 1;
  92504. _this._deviceToWorld = BABYLON.Matrix.Identity();
  92505. _this._worldToDevice = BABYLON.Matrix.Identity();
  92506. /**
  92507. * References to the webVR controllers for the vrDevice.
  92508. */
  92509. _this.controllers = [];
  92510. /**
  92511. * Emits an event when a controller is attached.
  92512. */
  92513. _this.onControllersAttachedObservable = new BABYLON.Observable();
  92514. /**
  92515. * Emits an event when a controller's mesh has been loaded;
  92516. */
  92517. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92518. /**
  92519. * Emits an event when the HMD's pose has been updated.
  92520. */
  92521. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  92522. _this._poseSet = false;
  92523. /**
  92524. * If the rig cameras be used as parent instead of this camera.
  92525. */
  92526. _this.rigParenting = true;
  92527. _this._defaultHeight = undefined;
  92528. _this._workingVector = BABYLON.Vector3.Zero();
  92529. _this._oneVector = BABYLON.Vector3.One();
  92530. _this._workingMatrix = BABYLON.Matrix.Identity();
  92531. _this._cache.position = BABYLON.Vector3.Zero();
  92532. if (webVROptions.defaultHeight) {
  92533. _this._defaultHeight = webVROptions.defaultHeight;
  92534. _this.position.y = _this._defaultHeight;
  92535. }
  92536. _this.minZ = 0.1;
  92537. //legacy support - the compensation boolean was removed.
  92538. if (arguments.length === 5) {
  92539. _this.webVROptions = arguments[4];
  92540. }
  92541. // default webVR options
  92542. if (_this.webVROptions.trackPosition == undefined) {
  92543. _this.webVROptions.trackPosition = true;
  92544. }
  92545. if (_this.webVROptions.controllerMeshes == undefined) {
  92546. _this.webVROptions.controllerMeshes = true;
  92547. }
  92548. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  92549. _this.webVROptions.defaultLightingOnControllers = true;
  92550. }
  92551. _this.rotationQuaternion = new BABYLON.Quaternion();
  92552. if (_this.webVROptions && _this.webVROptions.positionScale) {
  92553. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  92554. }
  92555. //enable VR
  92556. var engine = _this.getEngine();
  92557. _this._onVREnabled = function (success) { if (success) {
  92558. _this.initControllers();
  92559. } };
  92560. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  92561. engine.initWebVR().add(function (event) {
  92562. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  92563. return;
  92564. }
  92565. _this._vrDevice = event.vrDisplay;
  92566. //reset the rig parameters.
  92567. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  92568. if (_this._attached) {
  92569. _this.getEngine().enableVR();
  92570. }
  92571. });
  92572. if (typeof (VRFrameData) !== "undefined")
  92573. _this._frameData = new VRFrameData();
  92574. /**
  92575. * The idea behind the following lines:
  92576. * objects that have the camera as parent should actually have the rig cameras as a parent.
  92577. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  92578. * the second will not show it correctly.
  92579. *
  92580. * To solve this - each object that has the camera as parent will be added to a protected array.
  92581. * When the rig camera renders, it will take this array and set all of those to be its children.
  92582. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  92583. * Amazing!
  92584. */
  92585. scene.onBeforeCameraRenderObservable.add(function (camera) {
  92586. if (camera.parent === _this && _this.rigParenting) {
  92587. _this._descendants = _this.getDescendants(true, function (n) {
  92588. // don't take the cameras or the controllers!
  92589. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  92590. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  92591. return !isController && !isRigCamera;
  92592. });
  92593. _this._descendants.forEach(function (node) {
  92594. node.parent = camera;
  92595. });
  92596. }
  92597. });
  92598. scene.onAfterCameraRenderObservable.add(function (camera) {
  92599. if (camera.parent === _this && _this.rigParenting) {
  92600. _this._descendants.forEach(function (node) {
  92601. node.parent = _this;
  92602. });
  92603. }
  92604. });
  92605. return _this;
  92606. }
  92607. /**
  92608. * Gets the device distance from the ground in meters.
  92609. * @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.
  92610. */
  92611. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  92612. if (this._standingMatrix) {
  92613. // Add standing matrix offset to get real offset from ground in room
  92614. this._standingMatrix.getTranslationToRef(this._workingVector);
  92615. return this._deviceRoomPosition.y + this._workingVector.y;
  92616. }
  92617. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  92618. return this._defaultHeight || 0;
  92619. };
  92620. /**
  92621. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92622. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  92623. */
  92624. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  92625. var _this = this;
  92626. if (callback === void 0) { callback = function (bool) { }; }
  92627. // Use standing matrix if available
  92628. this.getEngine().initWebVRAsync().then(function (result) {
  92629. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  92630. callback(false);
  92631. }
  92632. else {
  92633. _this._standingMatrix = new BABYLON.Matrix();
  92634. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  92635. if (!_this.getScene().useRightHandedSystem) {
  92636. [2, 6, 8, 9, 14].forEach(function (num) {
  92637. if (_this._standingMatrix) {
  92638. _this._standingMatrix.m[num] *= -1;
  92639. }
  92640. });
  92641. }
  92642. callback(true);
  92643. }
  92644. });
  92645. };
  92646. /**
  92647. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92648. * @returns A promise with a boolean set to if the standing matrix is supported.
  92649. */
  92650. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  92651. var _this = this;
  92652. return new Promise(function (res, rej) {
  92653. _this.useStandingMatrix(function (supported) {
  92654. res(supported);
  92655. });
  92656. });
  92657. };
  92658. /**
  92659. * Disposes the camera
  92660. */
  92661. WebVRFreeCamera.prototype.dispose = function () {
  92662. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  92663. _super.prototype.dispose.call(this);
  92664. };
  92665. /**
  92666. * Gets a vrController by name.
  92667. * @param name The name of the controller to retreive
  92668. * @returns the controller matching the name specified or null if not found
  92669. */
  92670. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  92671. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  92672. var gp = _a[_i];
  92673. if (gp.hand === name) {
  92674. return gp;
  92675. }
  92676. }
  92677. return null;
  92678. };
  92679. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  92680. /**
  92681. * The controller corrisponding to the users left hand.
  92682. */
  92683. get: function () {
  92684. if (!this._leftController) {
  92685. this._leftController = this.getControllerByName("left");
  92686. }
  92687. return this._leftController;
  92688. },
  92689. enumerable: true,
  92690. configurable: true
  92691. });
  92692. ;
  92693. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  92694. /**
  92695. * The controller corrisponding to the users right hand.
  92696. */
  92697. get: function () {
  92698. if (!this._rightController) {
  92699. this._rightController = this.getControllerByName("right");
  92700. }
  92701. return this._rightController;
  92702. },
  92703. enumerable: true,
  92704. configurable: true
  92705. });
  92706. ;
  92707. /**
  92708. * Casts a ray forward from the vrCamera's gaze.
  92709. * @param length Length of the ray (default: 100)
  92710. * @returns the ray corrisponding to the gaze
  92711. */
  92712. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  92713. if (length === void 0) { length = 100; }
  92714. if (this.leftCamera) {
  92715. // Use left eye to avoid computation to compute center on every call
  92716. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  92717. }
  92718. else {
  92719. return _super.prototype.getForwardRay.call(this, length);
  92720. }
  92721. };
  92722. /**
  92723. * Updates the camera based on device's frame data
  92724. */
  92725. WebVRFreeCamera.prototype._checkInputs = function () {
  92726. if (this._vrDevice && this._vrDevice.isPresenting) {
  92727. this._vrDevice.getFrameData(this._frameData);
  92728. this.updateFromDevice(this._frameData.pose);
  92729. }
  92730. _super.prototype._checkInputs.call(this);
  92731. };
  92732. /**
  92733. * Updates the poseControlled values based on the input device pose.
  92734. * @param poseData Pose coming from the device
  92735. */
  92736. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  92737. if (poseData && poseData.orientation) {
  92738. this.rawPose = poseData;
  92739. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  92740. if (this.getScene().useRightHandedSystem) {
  92741. this._deviceRoomRotationQuaternion.z *= -1;
  92742. this._deviceRoomRotationQuaternion.w *= -1;
  92743. }
  92744. if (this.webVROptions.trackPosition && this.rawPose.position) {
  92745. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  92746. if (this.getScene().useRightHandedSystem) {
  92747. this._deviceRoomPosition.z *= -1;
  92748. }
  92749. }
  92750. this._poseSet = true;
  92751. }
  92752. };
  92753. /**
  92754. * WebVR's attach control will start broadcasting frames to the device.
  92755. * Note that in certain browsers (chrome for example) this function must be called
  92756. * within a user-interaction callback. Example:
  92757. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  92758. *
  92759. * @param element html element to attach the vrDevice to
  92760. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  92761. */
  92762. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  92763. _super.prototype.attachControl.call(this, element, noPreventDefault);
  92764. this._attached = true;
  92765. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  92766. if (this._vrDevice) {
  92767. this.getEngine().enableVR();
  92768. }
  92769. };
  92770. /**
  92771. * Detaches the camera from the html element and disables VR
  92772. *
  92773. * @param element html element to detach from
  92774. */
  92775. WebVRFreeCamera.prototype.detachControl = function (element) {
  92776. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  92777. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  92778. _super.prototype.detachControl.call(this, element);
  92779. this._attached = false;
  92780. this.getEngine().disableVR();
  92781. };
  92782. /**
  92783. * @returns the name of this class
  92784. */
  92785. WebVRFreeCamera.prototype.getClassName = function () {
  92786. return "WebVRFreeCamera";
  92787. };
  92788. /**
  92789. * Calls resetPose on the vrDisplay
  92790. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  92791. */
  92792. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  92793. //uses the vrDisplay's "resetPose()".
  92794. //pitch and roll won't be affected.
  92795. this._vrDevice.resetPose();
  92796. };
  92797. /**
  92798. * Updates the rig cameras (left and right eye)
  92799. */
  92800. WebVRFreeCamera.prototype._updateRigCameras = function () {
  92801. var camLeft = this._rigCameras[0];
  92802. var camRight = this._rigCameras[1];
  92803. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92804. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92805. camLeft.position.copyFrom(this._deviceRoomPosition);
  92806. camRight.position.copyFrom(this._deviceRoomPosition);
  92807. };
  92808. /**
  92809. * Updates the cached values of the camera
  92810. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  92811. */
  92812. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  92813. var _this = this;
  92814. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  92815. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  92816. if (!this.updateCacheCalled) {
  92817. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  92818. this.updateCacheCalled = true;
  92819. this.update();
  92820. }
  92821. // Set working vector to the device position in room space rotated by the new rotation
  92822. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  92823. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  92824. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  92825. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  92826. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  92827. // Add translation from anchor position
  92828. this._deviceToWorld.getTranslationToRef(this._workingVector);
  92829. this._workingVector.addInPlace(this.position);
  92830. this._workingVector.subtractInPlace(this._cache.position);
  92831. this._deviceToWorld.setTranslation(this._workingVector);
  92832. // Set an inverted matrix to be used when updating the camera
  92833. this._deviceToWorld.invertToRef(this._worldToDevice);
  92834. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  92835. this.controllers.forEach(function (controller) {
  92836. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  92837. controller.update();
  92838. });
  92839. }
  92840. if (!ignoreParentClass) {
  92841. _super.prototype._updateCache.call(this);
  92842. }
  92843. this.updateCacheCalled = false;
  92844. };
  92845. /**
  92846. * Updates the current device position and rotation in the babylon world
  92847. */
  92848. WebVRFreeCamera.prototype.update = function () {
  92849. // Get current device position in babylon world
  92850. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  92851. // Get current device rotation in babylon world
  92852. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  92853. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  92854. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  92855. if (this._poseSet) {
  92856. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  92857. }
  92858. _super.prototype.update.call(this);
  92859. };
  92860. /**
  92861. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  92862. * @returns an identity matrix
  92863. */
  92864. WebVRFreeCamera.prototype._getViewMatrix = function () {
  92865. return BABYLON.Matrix.Identity();
  92866. };
  92867. /**
  92868. * This function is called by the two RIG cameras.
  92869. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  92870. */
  92871. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  92872. var _this = this;
  92873. // Update the parent camera prior to using a child camera to avoid desynchronization
  92874. var parentCamera = this._cameraRigParams["parentCamera"];
  92875. parentCamera._updateCache();
  92876. //WebVR 1.1
  92877. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  92878. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  92879. if (!this.getScene().useRightHandedSystem) {
  92880. [2, 6, 8, 9, 14].forEach(function (num) {
  92881. _this._webvrViewMatrix.m[num] *= -1;
  92882. });
  92883. }
  92884. // update the camera rotation matrix
  92885. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  92886. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  92887. // Computing target and final matrix
  92888. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  92889. // should the view matrix be updated with scale and position offset?
  92890. if (parentCamera.deviceScaleFactor !== 1) {
  92891. this._webvrViewMatrix.invert();
  92892. // scale the position, if set
  92893. if (parentCamera.deviceScaleFactor) {
  92894. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  92895. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  92896. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  92897. }
  92898. this._webvrViewMatrix.invert();
  92899. }
  92900. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  92901. // Compute global position
  92902. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  92903. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  92904. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  92905. this._workingMatrix.getTranslationToRef(this._globalPosition);
  92906. this._markSyncedWithParent();
  92907. return this._webvrViewMatrix;
  92908. };
  92909. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  92910. var _this = this;
  92911. var parentCamera = this.parent;
  92912. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  92913. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  92914. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  92915. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  92916. //babylon compatible matrix
  92917. if (!this.getScene().useRightHandedSystem) {
  92918. [8, 9, 10, 11].forEach(function (num) {
  92919. _this._projectionMatrix.m[num] *= -1;
  92920. });
  92921. }
  92922. return this._projectionMatrix;
  92923. };
  92924. /**
  92925. * Initializes the controllers and their meshes
  92926. */
  92927. WebVRFreeCamera.prototype.initControllers = function () {
  92928. var _this = this;
  92929. this.controllers = [];
  92930. var manager = this.getScene().gamepadManager;
  92931. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  92932. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92933. var webVrController = gamepad;
  92934. if (webVrController.defaultModel) {
  92935. webVrController.defaultModel.setEnabled(false);
  92936. }
  92937. if (webVrController.hand === "right") {
  92938. _this._rightController = null;
  92939. }
  92940. if (webVrController.hand === "left") {
  92941. _this._leftController = null;
  92942. }
  92943. var controllerIndex = _this.controllers.indexOf(webVrController);
  92944. if (controllerIndex !== -1) {
  92945. _this.controllers.splice(controllerIndex, 1);
  92946. }
  92947. }
  92948. });
  92949. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  92950. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92951. var webVrController_1 = gamepad;
  92952. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  92953. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  92954. if (_this.webVROptions.controllerMeshes) {
  92955. if (webVrController_1.defaultModel) {
  92956. webVrController_1.defaultModel.setEnabled(true);
  92957. }
  92958. else {
  92959. // Load the meshes
  92960. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  92961. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  92962. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  92963. if (_this.webVROptions.defaultLightingOnControllers) {
  92964. if (!_this._lightOnControllers) {
  92965. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  92966. }
  92967. var activateLightOnSubMeshes_1 = function (mesh, light) {
  92968. var children = mesh.getChildren();
  92969. if (children.length !== 0) {
  92970. children.forEach(function (mesh) {
  92971. light.includedOnlyMeshes.push(mesh);
  92972. activateLightOnSubMeshes_1(mesh, light);
  92973. });
  92974. }
  92975. };
  92976. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  92977. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  92978. }
  92979. });
  92980. }
  92981. }
  92982. webVrController_1.attachToPoseControlledCamera(_this);
  92983. // since this is async - sanity check. Is the controller already stored?
  92984. if (_this.controllers.indexOf(webVrController_1) === -1) {
  92985. //add to the controllers array
  92986. _this.controllers.push(webVrController_1);
  92987. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  92988. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  92989. // So we're overriding setting left & right manually to be sure
  92990. var firstViveWandDetected = false;
  92991. for (var i = 0; i < _this.controllers.length; i++) {
  92992. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92993. if (!firstViveWandDetected) {
  92994. firstViveWandDetected = true;
  92995. _this.controllers[i].hand = "left";
  92996. }
  92997. else {
  92998. _this.controllers[i].hand = "right";
  92999. }
  93000. }
  93001. }
  93002. //did we find enough controllers? Great! let the developer know.
  93003. if (_this.controllers.length >= 2) {
  93004. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  93005. }
  93006. }
  93007. }
  93008. });
  93009. };
  93010. return WebVRFreeCamera;
  93011. }(BABYLON.FreeCamera));
  93012. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  93013. })(BABYLON || (BABYLON = {}));
  93014. //# sourceMappingURL=babylon.webVRCamera.js.map
  93015. var BABYLON;
  93016. (function (BABYLON) {
  93017. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  93018. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  93019. });
  93020. // We're mainly based on the logic defined into the FreeCamera code
  93021. /**
  93022. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  93023. * being tilted forward or back and left or right.
  93024. */
  93025. var DeviceOrientationCamera = /** @class */ (function (_super) {
  93026. __extends(DeviceOrientationCamera, _super);
  93027. /**
  93028. * Creates a new device orientation camera
  93029. * @param name The name of the camera
  93030. * @param position The start position camera
  93031. * @param scene The scene the camera belongs to
  93032. */
  93033. function DeviceOrientationCamera(name, position, scene) {
  93034. var _this = _super.call(this, name, position, scene) || this;
  93035. _this._quaternionCache = new BABYLON.Quaternion();
  93036. _this.inputs.addDeviceOrientation();
  93037. return _this;
  93038. }
  93039. /**
  93040. * Gets the current instance class name ("DeviceOrientationCamera").
  93041. * This helps avoiding instanceof at run time.
  93042. * @returns the class name
  93043. */
  93044. DeviceOrientationCamera.prototype.getClassName = function () {
  93045. return "DeviceOrientationCamera";
  93046. };
  93047. /**
  93048. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  93049. */
  93050. DeviceOrientationCamera.prototype._checkInputs = function () {
  93051. _super.prototype._checkInputs.call(this);
  93052. this._quaternionCache.copyFrom(this.rotationQuaternion);
  93053. if (this._initialQuaternion) {
  93054. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93055. }
  93056. };
  93057. /**
  93058. * Reset the camera to its default orientation on the specified axis only.
  93059. * @param axis The axis to reset
  93060. */
  93061. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  93062. var _this = this;
  93063. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  93064. //can only work if this camera has a rotation quaternion already.
  93065. if (!this.rotationQuaternion)
  93066. return;
  93067. if (!this._initialQuaternion) {
  93068. this._initialQuaternion = new BABYLON.Quaternion();
  93069. }
  93070. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  93071. ['x', 'y', 'z'].forEach(function (axisName) {
  93072. if (!axis[axisName]) {
  93073. _this._initialQuaternion[axisName] = 0;
  93074. }
  93075. else {
  93076. _this._initialQuaternion[axisName] *= -1;
  93077. }
  93078. });
  93079. this._initialQuaternion.normalize();
  93080. //force rotation update
  93081. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93082. };
  93083. return DeviceOrientationCamera;
  93084. }(BABYLON.FreeCamera));
  93085. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  93086. })(BABYLON || (BABYLON = {}));
  93087. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  93088. var BABYLON;
  93089. (function (BABYLON) {
  93090. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93091. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93092. });
  93093. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  93094. __extends(VRDeviceOrientationFreeCamera, _super);
  93095. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93096. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93097. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93098. var _this = _super.call(this, name, position, scene) || this;
  93099. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93100. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93101. return _this;
  93102. }
  93103. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  93104. return "VRDeviceOrientationFreeCamera";
  93105. };
  93106. return VRDeviceOrientationFreeCamera;
  93107. }(BABYLON.DeviceOrientationCamera));
  93108. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  93109. })(BABYLON || (BABYLON = {}));
  93110. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  93111. var BABYLON;
  93112. (function (BABYLON) {
  93113. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93114. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  93115. });
  93116. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  93117. __extends(VRDeviceOrientationArcRotateCamera, _super);
  93118. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  93119. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93120. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93121. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  93122. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93123. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93124. _this.inputs.addVRDeviceOrientation();
  93125. return _this;
  93126. }
  93127. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  93128. return "VRDeviceOrientationArcRotateCamera";
  93129. };
  93130. return VRDeviceOrientationArcRotateCamera;
  93131. }(BABYLON.ArcRotateCamera));
  93132. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  93133. })(BABYLON || (BABYLON = {}));
  93134. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  93135. var BABYLON;
  93136. (function (BABYLON) {
  93137. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  93138. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  93139. });
  93140. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  93141. __extends(VRDeviceOrientationGamepadCamera, _super);
  93142. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93143. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93144. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93145. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  93146. _this.inputs.addGamepad();
  93147. return _this;
  93148. }
  93149. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  93150. return "VRDeviceOrientationGamepadCamera";
  93151. };
  93152. return VRDeviceOrientationGamepadCamera;
  93153. }(BABYLON.VRDeviceOrientationFreeCamera));
  93154. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  93155. })(BABYLON || (BABYLON = {}));
  93156. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  93157. var BABYLON;
  93158. (function (BABYLON) {
  93159. var VRExperienceHelperGazer = /** @class */ (function () {
  93160. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  93161. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  93162. this.scene = scene;
  93163. this._pointerDownOnMeshAsked = false;
  93164. this._isActionableMesh = false;
  93165. this._teleportationRequestInitiated = false;
  93166. this._teleportationBackRequestInitiated = false;
  93167. this._rotationRightAsked = false;
  93168. this._rotationLeftAsked = false;
  93169. this._dpadPressed = true;
  93170. this._activePointer = false;
  93171. this._id = VRExperienceHelperGazer._idCounter++;
  93172. // Gaze tracker
  93173. if (!gazeTrackerToClone) {
  93174. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  93175. this._gazeTracker.bakeCurrentTransformIntoVertices();
  93176. this._gazeTracker.isPickable = false;
  93177. this._gazeTracker.isVisible = false;
  93178. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  93179. targetMat.specularColor = BABYLON.Color3.Black();
  93180. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93181. targetMat.backFaceCulling = false;
  93182. this._gazeTracker.material = targetMat;
  93183. }
  93184. else {
  93185. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  93186. }
  93187. }
  93188. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  93189. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  93190. };
  93191. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  93192. this._pointerDownOnMeshAsked = true;
  93193. if (this._currentHit) {
  93194. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  93195. }
  93196. };
  93197. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  93198. if (this._currentHit) {
  93199. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  93200. }
  93201. this._pointerDownOnMeshAsked = false;
  93202. };
  93203. VRExperienceHelperGazer.prototype._activatePointer = function () {
  93204. this._activePointer = true;
  93205. };
  93206. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  93207. this._activePointer = false;
  93208. };
  93209. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  93210. if (distance === void 0) { distance = 100; }
  93211. };
  93212. VRExperienceHelperGazer.prototype.dispose = function () {
  93213. this._interactionsEnabled = false;
  93214. this._teleportationEnabled = false;
  93215. if (this._gazeTracker) {
  93216. this._gazeTracker.dispose();
  93217. }
  93218. };
  93219. VRExperienceHelperGazer._idCounter = 0;
  93220. return VRExperienceHelperGazer;
  93221. }());
  93222. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  93223. __extends(VRExperienceHelperControllerGazer, _super);
  93224. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  93225. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  93226. _this.webVRController = webVRController;
  93227. // Laser pointer
  93228. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  93229. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  93230. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93231. laserPointerMaterial.alpha = 0.6;
  93232. _this._laserPointer.material = laserPointerMaterial;
  93233. _this._laserPointer.rotation.x = Math.PI / 2;
  93234. _this._laserPointer.position.z = -0.5;
  93235. _this._laserPointer.isVisible = false;
  93236. _this._laserPointer.isPickable = false;
  93237. if (!webVRController.mesh) {
  93238. // Create an empty mesh that is used prior to loading the high quality model
  93239. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  93240. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  93241. preloadPointerPose.rotation.x = -0.7;
  93242. preloadMesh.addChild(preloadPointerPose);
  93243. webVRController.attachToMesh(preloadMesh);
  93244. }
  93245. _this._setLaserPointerParent(webVRController.mesh);
  93246. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  93247. _this._setLaserPointerParent(mesh);
  93248. });
  93249. return _this;
  93250. }
  93251. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  93252. return this.webVRController.getForwardRay(length);
  93253. };
  93254. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  93255. _super.prototype._activatePointer.call(this);
  93256. this._laserPointer.isVisible = true;
  93257. };
  93258. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  93259. _super.prototype._deactivatePointer.call(this);
  93260. this._laserPointer.isVisible = false;
  93261. };
  93262. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  93263. this._laserPointer.material.emissiveColor = color;
  93264. };
  93265. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  93266. var makeNotPick = function (root) {
  93267. root.isPickable = false;
  93268. root.getChildMeshes().forEach(function (c) {
  93269. makeNotPick(c);
  93270. });
  93271. };
  93272. makeNotPick(mesh);
  93273. var childMeshes = mesh.getChildMeshes();
  93274. this.webVRController._pointingPoseNode = null;
  93275. for (var i = 0; i < childMeshes.length; i++) {
  93276. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  93277. mesh = childMeshes[i];
  93278. this.webVRController._pointingPoseNode = mesh;
  93279. break;
  93280. }
  93281. }
  93282. this._laserPointer.parent = mesh;
  93283. };
  93284. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  93285. if (distance === void 0) { distance = 100; }
  93286. this._laserPointer.scaling.y = distance;
  93287. this._laserPointer.position.z = -distance / 2;
  93288. };
  93289. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  93290. _super.prototype.dispose.call(this);
  93291. this._laserPointer.dispose();
  93292. if (this._meshAttachedObserver) {
  93293. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  93294. }
  93295. };
  93296. return VRExperienceHelperControllerGazer;
  93297. }(VRExperienceHelperGazer));
  93298. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  93299. __extends(VRExperienceHelperCameraGazer, _super);
  93300. function VRExperienceHelperCameraGazer(getCamera, scene) {
  93301. var _this = _super.call(this, scene) || this;
  93302. _this.getCamera = getCamera;
  93303. return _this;
  93304. }
  93305. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  93306. var camera = this.getCamera();
  93307. if (camera) {
  93308. return camera.getForwardRay(length);
  93309. }
  93310. else {
  93311. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  93312. }
  93313. };
  93314. return VRExperienceHelperCameraGazer;
  93315. }(VRExperienceHelperGazer));
  93316. /**
  93317. * Helps to quickly add VR support to an existing scene.
  93318. * See http://doc.babylonjs.com/how_to/webvr_helper
  93319. */
  93320. var VRExperienceHelper = /** @class */ (function () {
  93321. /**
  93322. * Instantiates a VRExperienceHelper.
  93323. * Helps to quickly add VR support to an existing scene.
  93324. * @param scene The scene the VRExperienceHelper belongs to.
  93325. * @param webVROptions Options to modify the vr experience helper's behavior.
  93326. */
  93327. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  93328. if (webVROptions === void 0) { webVROptions = {}; }
  93329. var _this = this;
  93330. this.webVROptions = webVROptions;
  93331. // Can the system support WebVR, even if a headset isn't plugged in?
  93332. this._webVRsupported = false;
  93333. // If WebVR is supported, is a headset plugged in and are we ready to present?
  93334. this._webVRready = false;
  93335. // Are we waiting for the requestPresent callback to complete?
  93336. this._webVRrequesting = false;
  93337. // Are we presenting to the headset right now?
  93338. this._webVRpresenting = false;
  93339. // Are we presenting in the fullscreen fallback?
  93340. this._fullscreenVRpresenting = false;
  93341. /**
  93342. * Observable raised when entering VR.
  93343. */
  93344. this.onEnteringVRObservable = new BABYLON.Observable();
  93345. /**
  93346. * Observable raised when exiting VR.
  93347. */
  93348. this.onExitingVRObservable = new BABYLON.Observable();
  93349. /**
  93350. * Observable raised when controller mesh is loaded.
  93351. */
  93352. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  93353. this._useCustomVRButton = false;
  93354. this._teleportationRequested = false;
  93355. this._teleportActive = false;
  93356. this._floorMeshesCollection = [];
  93357. this._rotationAllowed = true;
  93358. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  93359. this._isDefaultTeleportationTarget = true;
  93360. this._teleportationFillColor = "#444444";
  93361. this._teleportationBorderColor = "#FFFFFF";
  93362. this._rotationAngle = 0;
  93363. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  93364. this._padSensibilityUp = 0.65;
  93365. this._padSensibilityDown = 0.35;
  93366. this.leftController = null;
  93367. this.rightController = null;
  93368. /**
  93369. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  93370. */
  93371. this.onNewMeshSelected = new BABYLON.Observable();
  93372. /**
  93373. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  93374. */
  93375. this.onNewMeshPicked = new BABYLON.Observable();
  93376. /**
  93377. * Observable raised before camera teleportation
  93378. */
  93379. this.onBeforeCameraTeleport = new BABYLON.Observable();
  93380. /**
  93381. * Observable raised after camera teleportation
  93382. */
  93383. this.onAfterCameraTeleport = new BABYLON.Observable();
  93384. /**
  93385. * Observable raised when current selected mesh gets unselected
  93386. */
  93387. this.onSelectedMeshUnselected = new BABYLON.Observable();
  93388. /**
  93389. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  93390. */
  93391. this.teleportationEnabled = true;
  93392. this._teleportationInitialized = false;
  93393. this._interactionsEnabled = false;
  93394. this._interactionsRequested = false;
  93395. this._displayGaze = true;
  93396. this._displayLaserPointer = true;
  93397. this._onResize = function () {
  93398. _this.moveButtonToBottomRight();
  93399. if (_this._fullscreenVRpresenting && _this._webVRready) {
  93400. _this.exitVR();
  93401. }
  93402. };
  93403. this._onFullscreenChange = function () {
  93404. if (document.fullscreen !== undefined) {
  93405. _this._fullscreenVRpresenting = document.fullscreen;
  93406. }
  93407. else if (document.mozFullScreen !== undefined) {
  93408. _this._fullscreenVRpresenting = document.mozFullScreen;
  93409. }
  93410. else if (document.webkitIsFullScreen !== undefined) {
  93411. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  93412. }
  93413. else if (document.msIsFullScreen !== undefined) {
  93414. _this._fullscreenVRpresenting = document.msIsFullScreen;
  93415. }
  93416. else if (document.msFullscreenElement !== undefined) {
  93417. _this._fullscreenVRpresenting = document.msFullscreenElement;
  93418. }
  93419. if (!_this._fullscreenVRpresenting && _this._canvas) {
  93420. _this.exitVR();
  93421. if (!_this._useCustomVRButton) {
  93422. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  93423. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  93424. }
  93425. }
  93426. };
  93427. this.beforeRender = function () {
  93428. if (_this.leftController && _this.leftController._activePointer) {
  93429. _this._castRayAndSelectObject(_this.leftController);
  93430. }
  93431. if (_this.rightController && _this.rightController._activePointer) {
  93432. _this._castRayAndSelectObject(_this.rightController);
  93433. }
  93434. if (_this._noControllerIsActive) {
  93435. _this._castRayAndSelectObject(_this._cameraGazer);
  93436. }
  93437. else {
  93438. _this._cameraGazer._gazeTracker.isVisible = false;
  93439. }
  93440. };
  93441. this._onNewGamepadConnected = function (gamepad) {
  93442. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  93443. if (gamepad.leftStick) {
  93444. gamepad.onleftstickchanged(function (stickValues) {
  93445. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  93446. // Listening to classic/xbox gamepad only if no VR controller is active
  93447. if ((!_this.leftController && !_this.rightController) ||
  93448. ((_this.leftController && !_this.leftController._activePointer) &&
  93449. (_this.rightController && !_this.rightController._activePointer))) {
  93450. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  93451. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  93452. }
  93453. }
  93454. });
  93455. }
  93456. if (gamepad.rightStick) {
  93457. gamepad.onrightstickchanged(function (stickValues) {
  93458. if (_this._teleportationInitialized) {
  93459. _this._checkRotate(stickValues, _this._cameraGazer);
  93460. }
  93461. });
  93462. }
  93463. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  93464. gamepad.onbuttondown(function (buttonPressed) {
  93465. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  93466. _this._cameraGazer._selectionPointerDown();
  93467. }
  93468. });
  93469. gamepad.onbuttonup(function (buttonPressed) {
  93470. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  93471. _this._cameraGazer._selectionPointerUp();
  93472. }
  93473. });
  93474. }
  93475. }
  93476. else {
  93477. var webVRController = gamepad;
  93478. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  93479. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  93480. _this.rightController = controller;
  93481. }
  93482. else {
  93483. _this.leftController = controller;
  93484. }
  93485. _this._tryEnableInteractionOnController(controller);
  93486. }
  93487. };
  93488. // 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
  93489. this._tryEnableInteractionOnController = function (controller) {
  93490. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  93491. _this._enableInteractionOnController(controller);
  93492. }
  93493. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  93494. _this._enableTeleportationOnController(controller);
  93495. }
  93496. };
  93497. this._onNewGamepadDisconnected = function (gamepad) {
  93498. if (gamepad instanceof BABYLON.WebVRController) {
  93499. if (gamepad.hand === "left" && _this.leftController != null) {
  93500. _this.leftController.dispose();
  93501. _this.leftController = null;
  93502. }
  93503. if (gamepad.hand === "right" && _this.rightController != null) {
  93504. _this.rightController.dispose();
  93505. _this.rightController = null;
  93506. }
  93507. }
  93508. };
  93509. this._workingVector = BABYLON.Vector3.Zero();
  93510. this._workingQuaternion = BABYLON.Quaternion.Identity();
  93511. this._workingMatrix = BABYLON.Matrix.Identity();
  93512. this._scene = scene;
  93513. this._canvas = scene.getEngine().getRenderingCanvas();
  93514. // Parse options
  93515. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  93516. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  93517. }
  93518. if (webVROptions.createDeviceOrientationCamera === undefined) {
  93519. webVROptions.createDeviceOrientationCamera = true;
  93520. }
  93521. if (webVROptions.laserToggle === undefined) {
  93522. webVROptions.laserToggle = true;
  93523. }
  93524. if (webVROptions.defaultHeight === undefined) {
  93525. webVROptions.defaultHeight = 1.7;
  93526. }
  93527. if (webVROptions.useCustomVRButton) {
  93528. this._useCustomVRButton = true;
  93529. if (webVROptions.customVRButton) {
  93530. this._btnVR = webVROptions.customVRButton;
  93531. }
  93532. }
  93533. if (webVROptions.rayLength) {
  93534. this._rayLength = webVROptions.rayLength;
  93535. }
  93536. this._defaultHeight = webVROptions.defaultHeight;
  93537. if (webVROptions.positionScale) {
  93538. this._rayLength *= webVROptions.positionScale;
  93539. this._defaultHeight *= webVROptions.positionScale;
  93540. }
  93541. // Set position
  93542. if (this._scene.activeCamera) {
  93543. this._position = this._scene.activeCamera.position.clone();
  93544. }
  93545. else {
  93546. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  93547. }
  93548. // Set non-vr camera
  93549. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  93550. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  93551. // Copy data from existing camera
  93552. if (this._scene.activeCamera) {
  93553. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93554. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  93555. // Set rotation from previous camera
  93556. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  93557. var targetCamera = this._scene.activeCamera;
  93558. if (targetCamera.rotationQuaternion) {
  93559. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  93560. }
  93561. else {
  93562. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  93563. }
  93564. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  93565. }
  93566. }
  93567. this._scene.activeCamera = this._deviceOrientationCamera;
  93568. if (this._canvas) {
  93569. this._scene.activeCamera.attachControl(this._canvas);
  93570. }
  93571. }
  93572. else {
  93573. this._existingCamera = this._scene.activeCamera;
  93574. }
  93575. // Create VR cameras
  93576. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93577. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  93578. }
  93579. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  93580. this._webVRCamera.useStandingMatrix();
  93581. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  93582. // Create default button
  93583. if (!this._useCustomVRButton) {
  93584. this._btnVR = document.createElement("BUTTON");
  93585. this._btnVR.className = "babylonVRicon";
  93586. this._btnVR.id = "babylonVRiconbtn";
  93587. this._btnVR.title = "Click to switch to VR";
  93588. 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) }";
  93589. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  93590. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  93591. // css += ".babylonVRicon.vrdisplaysupported { }";
  93592. // css += ".babylonVRicon.vrdisplayready { }";
  93593. // css += ".babylonVRicon.vrdisplayrequesting { }";
  93594. var style = document.createElement('style');
  93595. style.appendChild(document.createTextNode(css));
  93596. document.getElementsByTagName('head')[0].appendChild(style);
  93597. this.moveButtonToBottomRight();
  93598. }
  93599. // VR button click event
  93600. if (this._btnVR) {
  93601. this._btnVR.addEventListener("click", function () {
  93602. if (!_this.isInVRMode) {
  93603. _this.enterVR();
  93604. }
  93605. else {
  93606. _this.exitVR();
  93607. }
  93608. });
  93609. }
  93610. // Window events
  93611. window.addEventListener("resize", this._onResize);
  93612. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  93613. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  93614. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  93615. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  93616. document.onmsfullscreenchange = this._onFullscreenChange;
  93617. // Display vr button when headset is connected
  93618. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93619. this.displayVRButton();
  93620. }
  93621. else {
  93622. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  93623. if (e.vrDisplay) {
  93624. _this.displayVRButton();
  93625. }
  93626. });
  93627. }
  93628. // Exiting VR mode using 'ESC' key on desktop
  93629. this._onKeyDown = function (event) {
  93630. if (event.keyCode === 27 && _this.isInVRMode) {
  93631. _this.exitVR();
  93632. }
  93633. };
  93634. document.addEventListener("keydown", this._onKeyDown);
  93635. // Exiting VR mode double tapping the touch screen
  93636. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  93637. if (_this.isInVRMode) {
  93638. _this.exitVR();
  93639. if (_this._fullscreenVRpresenting) {
  93640. _this._scene.getEngine().switchFullscreen(true);
  93641. }
  93642. }
  93643. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  93644. // Listen for WebVR display changes
  93645. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  93646. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  93647. this._onVRRequestPresentStart = function () {
  93648. _this._webVRrequesting = true;
  93649. _this.updateButtonVisibility();
  93650. };
  93651. this._onVRRequestPresentComplete = function (success) {
  93652. _this._webVRrequesting = false;
  93653. _this.updateButtonVisibility();
  93654. };
  93655. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  93656. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  93657. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  93658. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93659. scene.onDisposeObservable.add(function () {
  93660. _this.dispose();
  93661. });
  93662. // Gamepad connection events
  93663. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  93664. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  93665. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  93666. this.updateButtonVisibility();
  93667. //create easing functions
  93668. this._circleEase = new BABYLON.CircleEase();
  93669. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93670. if (this.webVROptions.floorMeshes) {
  93671. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  93672. }
  93673. }
  93674. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  93675. /** Return this.onEnteringVRObservable
  93676. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  93677. */
  93678. get: function () {
  93679. return this.onEnteringVRObservable;
  93680. },
  93681. enumerable: true,
  93682. configurable: true
  93683. });
  93684. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  93685. /** Return this.onExitingVRObservable
  93686. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  93687. */
  93688. get: function () {
  93689. return this.onExitingVRObservable;
  93690. },
  93691. enumerable: true,
  93692. configurable: true
  93693. });
  93694. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  93695. /** Return this.onControllerMeshLoadedObservable
  93696. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  93697. */
  93698. get: function () {
  93699. return this.onControllerMeshLoadedObservable;
  93700. },
  93701. enumerable: true,
  93702. configurable: true
  93703. });
  93704. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  93705. /**
  93706. * The mesh used to display where the user is going to teleport.
  93707. */
  93708. get: function () {
  93709. return this._teleportationTarget;
  93710. },
  93711. /**
  93712. * Sets the mesh to be used to display where the user is going to teleport.
  93713. */
  93714. set: function (value) {
  93715. if (value) {
  93716. value.name = "teleportationTarget";
  93717. this._isDefaultTeleportationTarget = false;
  93718. this._teleportationTarget = value;
  93719. }
  93720. },
  93721. enumerable: true,
  93722. configurable: true
  93723. });
  93724. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  93725. /**
  93726. * The mesh used to display where the user is selecting,
  93727. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  93728. * See http://doc.babylonjs.com/resources/baking_transformations
  93729. */
  93730. get: function () {
  93731. return this._cameraGazer._gazeTracker;
  93732. },
  93733. set: function (value) {
  93734. if (value) {
  93735. this._cameraGazer._gazeTracker = value;
  93736. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  93737. this._cameraGazer._gazeTracker.isPickable = false;
  93738. this._cameraGazer._gazeTracker.isVisible = false;
  93739. this._cameraGazer._gazeTracker.name = "gazeTracker";
  93740. if (this.leftController) {
  93741. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93742. }
  93743. if (this.rightController) {
  93744. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93745. }
  93746. }
  93747. },
  93748. enumerable: true,
  93749. configurable: true
  93750. });
  93751. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  93752. /**
  93753. * If the ray of the gaze should be displayed.
  93754. */
  93755. get: function () {
  93756. return this._displayGaze;
  93757. },
  93758. /**
  93759. * Sets if the ray of the gaze should be displayed.
  93760. */
  93761. set: function (value) {
  93762. this._displayGaze = value;
  93763. if (!value) {
  93764. this._cameraGazer._gazeTracker.isVisible = false;
  93765. if (this.leftController) {
  93766. this.leftController._gazeTracker.isVisible = false;
  93767. }
  93768. if (this.rightController) {
  93769. this.rightController._gazeTracker.isVisible = false;
  93770. }
  93771. }
  93772. },
  93773. enumerable: true,
  93774. configurable: true
  93775. });
  93776. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  93777. /**
  93778. * If the ray of the LaserPointer should be displayed.
  93779. */
  93780. get: function () {
  93781. return this._displayLaserPointer;
  93782. },
  93783. /**
  93784. * Sets if the ray of the LaserPointer should be displayed.
  93785. */
  93786. set: function (value) {
  93787. this._displayLaserPointer = value;
  93788. if (!value) {
  93789. if (this.rightController) {
  93790. this.rightController._deactivatePointer();
  93791. this.rightController._gazeTracker.isVisible = false;
  93792. }
  93793. if (this.leftController) {
  93794. this.leftController._deactivatePointer();
  93795. this.leftController._gazeTracker.isVisible = false;
  93796. }
  93797. }
  93798. else {
  93799. if (this.rightController) {
  93800. this.rightController._activatePointer();
  93801. }
  93802. if (this.leftController) {
  93803. this.leftController._activatePointer();
  93804. }
  93805. }
  93806. },
  93807. enumerable: true,
  93808. configurable: true
  93809. });
  93810. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  93811. /**
  93812. * The deviceOrientationCamera used as the camera when not in VR.
  93813. */
  93814. get: function () {
  93815. return this._deviceOrientationCamera;
  93816. },
  93817. enumerable: true,
  93818. configurable: true
  93819. });
  93820. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  93821. /**
  93822. * Based on the current WebVR support, returns the current VR camera used.
  93823. */
  93824. get: function () {
  93825. if (this._webVRready) {
  93826. return this._webVRCamera;
  93827. }
  93828. else {
  93829. return this._scene.activeCamera;
  93830. }
  93831. },
  93832. enumerable: true,
  93833. configurable: true
  93834. });
  93835. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  93836. /**
  93837. * The webVRCamera which is used when in VR.
  93838. */
  93839. get: function () {
  93840. return this._webVRCamera;
  93841. },
  93842. enumerable: true,
  93843. configurable: true
  93844. });
  93845. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  93846. /**
  93847. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  93848. */
  93849. get: function () {
  93850. return this._vrDeviceOrientationCamera;
  93851. },
  93852. enumerable: true,
  93853. configurable: true
  93854. });
  93855. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  93856. get: function () {
  93857. var result = this._cameraGazer._teleportationRequestInitiated
  93858. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  93859. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  93860. return result;
  93861. },
  93862. enumerable: true,
  93863. configurable: true
  93864. });
  93865. // Raised when one of the controller has loaded successfully its associated default mesh
  93866. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  93867. if (this.leftController && this.leftController.webVRController == webVRController) {
  93868. if (webVRController.mesh) {
  93869. this.leftController._setLaserPointerParent(webVRController.mesh);
  93870. }
  93871. }
  93872. if (this.rightController && this.rightController.webVRController == webVRController) {
  93873. if (webVRController.mesh) {
  93874. this.rightController._setLaserPointerParent(webVRController.mesh);
  93875. }
  93876. }
  93877. try {
  93878. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  93879. }
  93880. catch (err) {
  93881. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  93882. }
  93883. };
  93884. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  93885. /**
  93886. * Gets a value indicating if we are currently in VR mode.
  93887. */
  93888. get: function () {
  93889. return this._webVRpresenting || this._fullscreenVRpresenting;
  93890. },
  93891. enumerable: true,
  93892. configurable: true
  93893. });
  93894. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  93895. var vrDisplay = this._scene.getEngine().getVRDevice();
  93896. if (vrDisplay) {
  93897. var wasPresenting = this._webVRpresenting;
  93898. // A VR display is connected
  93899. this._webVRpresenting = vrDisplay.isPresenting;
  93900. if (wasPresenting && !this._webVRpresenting)
  93901. this.exitVR();
  93902. }
  93903. else {
  93904. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  93905. }
  93906. this.updateButtonVisibility();
  93907. };
  93908. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  93909. this._webVRsupported = eventArgs.vrSupported;
  93910. this._webVRready = !!eventArgs.vrDisplay;
  93911. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  93912. this.updateButtonVisibility();
  93913. };
  93914. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  93915. if (this._canvas && !this._useCustomVRButton) {
  93916. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  93917. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  93918. }
  93919. };
  93920. VRExperienceHelper.prototype.displayVRButton = function () {
  93921. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  93922. document.body.appendChild(this._btnVR);
  93923. this._btnVRDisplayed = true;
  93924. }
  93925. };
  93926. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  93927. if (!this._btnVR || this._useCustomVRButton) {
  93928. return;
  93929. }
  93930. this._btnVR.className = "babylonVRicon";
  93931. if (this.isInVRMode) {
  93932. this._btnVR.className += " vrdisplaypresenting";
  93933. }
  93934. else {
  93935. if (this._webVRready)
  93936. this._btnVR.className += " vrdisplayready";
  93937. if (this._webVRsupported)
  93938. this._btnVR.className += " vrdisplaysupported";
  93939. if (this._webVRrequesting)
  93940. this._btnVR.className += " vrdisplayrequesting";
  93941. }
  93942. };
  93943. /**
  93944. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  93945. * Otherwise, will use the fullscreen API.
  93946. */
  93947. VRExperienceHelper.prototype.enterVR = function () {
  93948. if (this.onEnteringVRObservable) {
  93949. try {
  93950. this.onEnteringVRObservable.notifyObservers(this);
  93951. }
  93952. catch (err) {
  93953. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  93954. }
  93955. }
  93956. if (this._scene.activeCamera) {
  93957. this._position = this._scene.activeCamera.position.clone();
  93958. // make sure that we return to the last active camera
  93959. this._existingCamera = this._scene.activeCamera;
  93960. }
  93961. if (this._webVRrequesting)
  93962. return;
  93963. // If WebVR is supported and a headset is connected
  93964. if (this._webVRready) {
  93965. if (!this._webVRpresenting) {
  93966. this._webVRCamera.position = this._position;
  93967. this._scene.activeCamera = this._webVRCamera;
  93968. }
  93969. }
  93970. else if (this._vrDeviceOrientationCamera) {
  93971. this._vrDeviceOrientationCamera.position = this._position;
  93972. if (this._scene.activeCamera) {
  93973. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93974. }
  93975. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  93976. this._scene.getEngine().switchFullscreen(true);
  93977. this.updateButtonVisibility();
  93978. }
  93979. if (this._scene.activeCamera && this._canvas) {
  93980. this._scene.activeCamera.attachControl(this._canvas);
  93981. }
  93982. if (this._interactionsEnabled) {
  93983. this._scene.registerBeforeRender(this.beforeRender);
  93984. }
  93985. };
  93986. /**
  93987. * Attempt to exit VR, or fullscreen.
  93988. */
  93989. VRExperienceHelper.prototype.exitVR = function () {
  93990. if (this.onExitingVRObservable) {
  93991. try {
  93992. this.onExitingVRObservable.notifyObservers(this);
  93993. }
  93994. catch (err) {
  93995. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  93996. }
  93997. }
  93998. if (this._webVRpresenting) {
  93999. this._scene.getEngine().disableVR();
  94000. }
  94001. if (this._scene.activeCamera) {
  94002. this._position = this._scene.activeCamera.position.clone();
  94003. }
  94004. if (this._deviceOrientationCamera) {
  94005. this._deviceOrientationCamera.position = this._position;
  94006. this._scene.activeCamera = this._deviceOrientationCamera;
  94007. if (this._canvas) {
  94008. this._scene.activeCamera.attachControl(this._canvas);
  94009. }
  94010. }
  94011. else if (this._existingCamera) {
  94012. this._existingCamera.position = this._position;
  94013. this._scene.activeCamera = this._existingCamera;
  94014. }
  94015. this.updateButtonVisibility();
  94016. if (this._interactionsEnabled) {
  94017. this._scene.unregisterBeforeRender(this.beforeRender);
  94018. }
  94019. // resize to update width and height when exiting vr exits fullscreen
  94020. this._scene.getEngine().resize();
  94021. };
  94022. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  94023. /**
  94024. * The position of the vr experience helper.
  94025. */
  94026. get: function () {
  94027. return this._position;
  94028. },
  94029. /**
  94030. * Sets the position of the vr experience helper.
  94031. */
  94032. set: function (value) {
  94033. this._position = value;
  94034. if (this._scene.activeCamera) {
  94035. this._scene.activeCamera.position = value;
  94036. }
  94037. },
  94038. enumerable: true,
  94039. configurable: true
  94040. });
  94041. /**
  94042. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  94043. */
  94044. VRExperienceHelper.prototype.enableInteractions = function () {
  94045. var _this = this;
  94046. if (!this._interactionsEnabled) {
  94047. this._interactionsRequested = true;
  94048. if (this.leftController) {
  94049. this._enableInteractionOnController(this.leftController);
  94050. }
  94051. if (this.rightController) {
  94052. this._enableInteractionOnController(this.rightController);
  94053. }
  94054. this.raySelectionPredicate = function (mesh) {
  94055. return mesh.isVisible && mesh.isPickable;
  94056. };
  94057. this.meshSelectionPredicate = function (mesh) {
  94058. return true;
  94059. };
  94060. this._raySelectionPredicate = function (mesh) {
  94061. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  94062. && mesh.name.indexOf("teleportationTarget") === -1
  94063. && mesh.name.indexOf("torusTeleportation") === -1)) {
  94064. return _this.raySelectionPredicate(mesh);
  94065. }
  94066. return false;
  94067. };
  94068. this._interactionsEnabled = true;
  94069. }
  94070. };
  94071. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  94072. get: function () {
  94073. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  94074. },
  94075. enumerable: true,
  94076. configurable: true
  94077. });
  94078. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  94079. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  94080. if (this._floorMeshesCollection[i].id === mesh.id) {
  94081. return true;
  94082. }
  94083. }
  94084. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  94085. return true;
  94086. }
  94087. return false;
  94088. };
  94089. /**
  94090. * Adds a floor mesh to be used for teleportation.
  94091. * @param floorMesh the mesh to be used for teleportation.
  94092. */
  94093. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  94094. if (!this._floorMeshesCollection) {
  94095. return;
  94096. }
  94097. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  94098. return;
  94099. }
  94100. this._floorMeshesCollection.push(floorMesh);
  94101. };
  94102. /**
  94103. * Removes a floor mesh from being used for teleportation.
  94104. * @param floorMesh the mesh to be removed.
  94105. */
  94106. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  94107. if (!this._floorMeshesCollection) {
  94108. return;
  94109. }
  94110. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  94111. if (meshIndex !== -1) {
  94112. this._floorMeshesCollection.splice(meshIndex, 1);
  94113. }
  94114. };
  94115. /**
  94116. * Enables interactions and teleportation using the VR controllers and gaze.
  94117. * @param vrTeleportationOptions options to modify teleportation behavior.
  94118. */
  94119. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  94120. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  94121. if (!this._teleportationInitialized) {
  94122. this._teleportationRequested = true;
  94123. this.enableInteractions();
  94124. if (vrTeleportationOptions.floorMeshName) {
  94125. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  94126. }
  94127. if (vrTeleportationOptions.floorMeshes) {
  94128. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  94129. }
  94130. if (this.leftController != null) {
  94131. this._enableTeleportationOnController(this.leftController);
  94132. }
  94133. if (this.rightController != null) {
  94134. this._enableTeleportationOnController(this.rightController);
  94135. }
  94136. // Creates an image processing post process for the vignette not relying
  94137. // on the main scene configuration for image processing to reduce setup and spaces
  94138. // (gamma/linear) conflicts.
  94139. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  94140. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  94141. imageProcessingConfiguration.vignetteEnabled = true;
  94142. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  94143. this._webVRCamera.detachPostProcess(this._postProcessMove);
  94144. this._teleportationInitialized = true;
  94145. if (this._isDefaultTeleportationTarget) {
  94146. this._createTeleportationCircles();
  94147. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  94148. }
  94149. }
  94150. };
  94151. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  94152. var _this = this;
  94153. var controllerMesh = controller.webVRController.mesh;
  94154. if (controllerMesh) {
  94155. controller._interactionsEnabled = true;
  94156. controller._activatePointer();
  94157. if (this.webVROptions.laserToggle) {
  94158. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  94159. // Enabling / disabling laserPointer
  94160. if (_this._displayLaserPointer && stateObject.value === 1) {
  94161. if (controller._activePointer) {
  94162. controller._deactivatePointer();
  94163. }
  94164. else {
  94165. controller._activatePointer();
  94166. }
  94167. if (_this.displayGaze) {
  94168. controller._gazeTracker.isVisible = controller._activePointer;
  94169. }
  94170. }
  94171. });
  94172. }
  94173. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  94174. var gazer = controller;
  94175. if (_this._noControllerIsActive) {
  94176. gazer = _this._cameraGazer;
  94177. }
  94178. if (!gazer._pointerDownOnMeshAsked) {
  94179. if (stateObject.value > _this._padSensibilityUp) {
  94180. gazer._selectionPointerDown();
  94181. }
  94182. }
  94183. else if (stateObject.value < _this._padSensibilityDown) {
  94184. gazer._selectionPointerUp();
  94185. }
  94186. });
  94187. }
  94188. };
  94189. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  94190. // Dont teleport if another gaze already requested teleportation
  94191. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  94192. return;
  94193. }
  94194. if (!gazer._teleportationRequestInitiated) {
  94195. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  94196. gazer._activatePointer();
  94197. gazer._teleportationRequestInitiated = true;
  94198. }
  94199. }
  94200. else {
  94201. // Listening to the proper controller values changes to confirm teleportation
  94202. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  94203. if (this._teleportActive) {
  94204. this._teleportCamera(this._haloCenter);
  94205. }
  94206. gazer._teleportationRequestInitiated = false;
  94207. }
  94208. }
  94209. };
  94210. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  94211. // Only rotate when user is not currently selecting a teleportation location
  94212. if (gazer._teleportationRequestInitiated) {
  94213. return;
  94214. }
  94215. if (!gazer._rotationLeftAsked) {
  94216. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  94217. gazer._rotationLeftAsked = true;
  94218. if (this._rotationAllowed) {
  94219. this._rotateCamera(false);
  94220. }
  94221. }
  94222. }
  94223. else {
  94224. if (stateObject.x > -this._padSensibilityDown) {
  94225. gazer._rotationLeftAsked = false;
  94226. }
  94227. }
  94228. if (!gazer._rotationRightAsked) {
  94229. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  94230. gazer._rotationRightAsked = true;
  94231. if (this._rotationAllowed) {
  94232. this._rotateCamera(true);
  94233. }
  94234. }
  94235. }
  94236. else {
  94237. if (stateObject.x < this._padSensibilityDown) {
  94238. gazer._rotationRightAsked = false;
  94239. }
  94240. }
  94241. };
  94242. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  94243. // Only teleport backwards when user is not currently selecting a teleportation location
  94244. if (gazer._teleportationRequestInitiated) {
  94245. return;
  94246. }
  94247. // Teleport backwards
  94248. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  94249. if (!gazer._teleportationBackRequestInitiated) {
  94250. if (!this.currentVRCamera) {
  94251. return;
  94252. }
  94253. // Get rotation and position of the current camera
  94254. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  94255. var position = this.currentVRCamera.position;
  94256. // If the camera has device position, use that instead
  94257. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  94258. rotation = this.currentVRCamera.deviceRotationQuaternion;
  94259. position = this.currentVRCamera.devicePosition;
  94260. }
  94261. // Get matrix with only the y rotation of the device rotation
  94262. rotation.toEulerAnglesToRef(this._workingVector);
  94263. this._workingVector.z = 0;
  94264. this._workingVector.x = 0;
  94265. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  94266. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  94267. // Rotate backwards ray by device rotation to cast at the ground behind the user
  94268. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  94269. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  94270. var ray = new BABYLON.Ray(position, this._workingVector);
  94271. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94272. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  94273. this._teleportCamera(hit.pickedPoint);
  94274. }
  94275. gazer._teleportationBackRequestInitiated = true;
  94276. }
  94277. }
  94278. else {
  94279. gazer._teleportationBackRequestInitiated = false;
  94280. }
  94281. };
  94282. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  94283. var _this = this;
  94284. var controllerMesh = controller.webVRController.mesh;
  94285. if (controllerMesh) {
  94286. if (!controller._interactionsEnabled) {
  94287. this._enableInteractionOnController(controller);
  94288. }
  94289. controller._interactionsEnabled = true;
  94290. controller._teleportationEnabled = true;
  94291. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  94292. controller._dpadPressed = false;
  94293. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  94294. controller._dpadPressed = stateObject.pressed;
  94295. if (!controller._dpadPressed) {
  94296. controller._rotationLeftAsked = false;
  94297. controller._rotationRightAsked = false;
  94298. controller._teleportationBackRequestInitiated = false;
  94299. }
  94300. });
  94301. }
  94302. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  94303. if (_this.teleportationEnabled) {
  94304. _this._checkTeleportBackwards(stateObject, controller);
  94305. _this._checkTeleportWithRay(stateObject, controller);
  94306. }
  94307. _this._checkRotate(stateObject, controller);
  94308. });
  94309. }
  94310. };
  94311. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  94312. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  94313. this._teleportationTarget.isPickable = false;
  94314. var length = 512;
  94315. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  94316. dynamicTexture.hasAlpha = true;
  94317. var context = dynamicTexture.getContext();
  94318. var centerX = length / 2;
  94319. var centerY = length / 2;
  94320. var radius = 200;
  94321. context.beginPath();
  94322. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  94323. context.fillStyle = this._teleportationFillColor;
  94324. context.fill();
  94325. context.lineWidth = 10;
  94326. context.strokeStyle = this._teleportationBorderColor;
  94327. context.stroke();
  94328. context.closePath();
  94329. dynamicTexture.update();
  94330. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  94331. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  94332. this._teleportationTarget.material = teleportationCircleMaterial;
  94333. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  94334. torus.isPickable = false;
  94335. torus.parent = this._teleportationTarget;
  94336. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  94337. var keys = [];
  94338. keys.push({
  94339. frame: 0,
  94340. value: 0
  94341. });
  94342. keys.push({
  94343. frame: 30,
  94344. value: 0.4
  94345. });
  94346. keys.push({
  94347. frame: 60,
  94348. value: 0
  94349. });
  94350. animationInnerCircle.setKeys(keys);
  94351. var easingFunction = new BABYLON.SineEase();
  94352. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  94353. animationInnerCircle.setEasingFunction(easingFunction);
  94354. torus.animations = [];
  94355. torus.animations.push(animationInnerCircle);
  94356. this._scene.beginAnimation(torus, 0, 60, true);
  94357. this._hideTeleportationTarget();
  94358. };
  94359. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  94360. this._teleportActive = true;
  94361. if (this._teleportationInitialized) {
  94362. this._teleportationTarget.isVisible = true;
  94363. if (this._isDefaultTeleportationTarget) {
  94364. this._teleportationTarget.getChildren()[0].isVisible = true;
  94365. }
  94366. }
  94367. };
  94368. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  94369. this._teleportActive = false;
  94370. if (this._teleportationInitialized) {
  94371. this._teleportationTarget.isVisible = false;
  94372. if (this._isDefaultTeleportationTarget) {
  94373. this._teleportationTarget.getChildren()[0].isVisible = false;
  94374. }
  94375. }
  94376. };
  94377. VRExperienceHelper.prototype._rotateCamera = function (right) {
  94378. var _this = this;
  94379. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94380. return;
  94381. }
  94382. if (right) {
  94383. this._rotationAngle++;
  94384. }
  94385. else {
  94386. this._rotationAngle--;
  94387. }
  94388. this.currentVRCamera.animations = [];
  94389. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  94390. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94391. var animationRotationKeys = [];
  94392. animationRotationKeys.push({
  94393. frame: 0,
  94394. value: this.currentVRCamera.rotationQuaternion
  94395. });
  94396. animationRotationKeys.push({
  94397. frame: 6,
  94398. value: target
  94399. });
  94400. animationRotation.setKeys(animationRotationKeys);
  94401. animationRotation.setEasingFunction(this._circleEase);
  94402. this.currentVRCamera.animations.push(animationRotation);
  94403. this._postProcessMove.animations = [];
  94404. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94405. var vignetteWeightKeys = [];
  94406. vignetteWeightKeys.push({
  94407. frame: 0,
  94408. value: 0
  94409. });
  94410. vignetteWeightKeys.push({
  94411. frame: 3,
  94412. value: 4
  94413. });
  94414. vignetteWeightKeys.push({
  94415. frame: 6,
  94416. value: 0
  94417. });
  94418. animationPP.setKeys(vignetteWeightKeys);
  94419. animationPP.setEasingFunction(this._circleEase);
  94420. this._postProcessMove.animations.push(animationPP);
  94421. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94422. var vignetteStretchKeys = [];
  94423. vignetteStretchKeys.push({
  94424. frame: 0,
  94425. value: 0
  94426. });
  94427. vignetteStretchKeys.push({
  94428. frame: 3,
  94429. value: 10
  94430. });
  94431. vignetteStretchKeys.push({
  94432. frame: 6,
  94433. value: 0
  94434. });
  94435. animationPP2.setKeys(vignetteStretchKeys);
  94436. animationPP2.setEasingFunction(this._circleEase);
  94437. this._postProcessMove.animations.push(animationPP2);
  94438. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94439. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94440. this._postProcessMove.samples = 4;
  94441. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94442. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  94443. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94444. });
  94445. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  94446. };
  94447. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  94448. if (hit.pickedPoint) {
  94449. if (gazer._teleportationRequestInitiated) {
  94450. this._displayTeleportationTarget();
  94451. this._haloCenter.copyFrom(hit.pickedPoint);
  94452. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  94453. }
  94454. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  94455. if (pickNormal) {
  94456. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94457. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94458. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  94459. }
  94460. this._teleportationTarget.position.y += 0.1;
  94461. }
  94462. };
  94463. VRExperienceHelper.prototype._teleportCamera = function (location) {
  94464. var _this = this;
  94465. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94466. return;
  94467. }
  94468. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  94469. // offset of the headset from the anchor.
  94470. if (this.webVRCamera.leftCamera) {
  94471. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  94472. this._workingVector.subtractInPlace(this.webVRCamera.position);
  94473. location.subtractToRef(this._workingVector, this._workingVector);
  94474. }
  94475. else {
  94476. this._workingVector.copyFrom(location);
  94477. }
  94478. // Add height to account for user's height offset
  94479. if (this.isInVRMode) {
  94480. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  94481. }
  94482. else {
  94483. this._workingVector.y += this._defaultHeight;
  94484. }
  94485. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  94486. // Create animation from the camera's position to the new location
  94487. this.currentVRCamera.animations = [];
  94488. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94489. var animationCameraTeleportationKeys = [{
  94490. frame: 0,
  94491. value: this.currentVRCamera.position
  94492. },
  94493. {
  94494. frame: 11,
  94495. value: this._workingVector
  94496. }
  94497. ];
  94498. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  94499. animationCameraTeleportation.setEasingFunction(this._circleEase);
  94500. this.currentVRCamera.animations.push(animationCameraTeleportation);
  94501. this._postProcessMove.animations = [];
  94502. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94503. var vignetteWeightKeys = [];
  94504. vignetteWeightKeys.push({
  94505. frame: 0,
  94506. value: 0
  94507. });
  94508. vignetteWeightKeys.push({
  94509. frame: 5,
  94510. value: 8
  94511. });
  94512. vignetteWeightKeys.push({
  94513. frame: 11,
  94514. value: 0
  94515. });
  94516. animationPP.setKeys(vignetteWeightKeys);
  94517. this._postProcessMove.animations.push(animationPP);
  94518. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94519. var vignetteStretchKeys = [];
  94520. vignetteStretchKeys.push({
  94521. frame: 0,
  94522. value: 0
  94523. });
  94524. vignetteStretchKeys.push({
  94525. frame: 5,
  94526. value: 10
  94527. });
  94528. vignetteStretchKeys.push({
  94529. frame: 11,
  94530. value: 0
  94531. });
  94532. animationPP2.setKeys(vignetteStretchKeys);
  94533. this._postProcessMove.animations.push(animationPP2);
  94534. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94535. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94536. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94537. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  94538. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94539. });
  94540. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  94541. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  94542. });
  94543. this._hideTeleportationTarget();
  94544. };
  94545. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  94546. if (normal) {
  94547. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  94548. if (angle < Math.PI / 2) {
  94549. normal.scaleInPlace(-1);
  94550. }
  94551. }
  94552. return normal;
  94553. };
  94554. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  94555. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94556. return;
  94557. }
  94558. var ray = gazer._getForwardRay(this._rayLength);
  94559. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94560. if (hit) {
  94561. // Populate the contrllers mesh that can be used for drag/drop
  94562. if (gazer._laserPointer) {
  94563. hit.originMesh = gazer._laserPointer.parent;
  94564. }
  94565. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  94566. }
  94567. gazer._currentHit = hit;
  94568. // Moving the gazeTracker on the mesh face targetted
  94569. if (hit && hit.pickedPoint) {
  94570. if (this._displayGaze) {
  94571. var multiplier = 1;
  94572. gazer._gazeTracker.isVisible = true;
  94573. if (gazer._isActionableMesh) {
  94574. multiplier = 3;
  94575. }
  94576. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  94577. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  94578. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  94579. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  94580. // To avoid z-fighting
  94581. var deltaFighting = 0.002;
  94582. if (pickNormal) {
  94583. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94584. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94585. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  94586. }
  94587. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  94588. if (gazer._gazeTracker.position.x < 0) {
  94589. gazer._gazeTracker.position.x += deltaFighting;
  94590. }
  94591. else {
  94592. gazer._gazeTracker.position.x -= deltaFighting;
  94593. }
  94594. if (gazer._gazeTracker.position.y < 0) {
  94595. gazer._gazeTracker.position.y += deltaFighting;
  94596. }
  94597. else {
  94598. gazer._gazeTracker.position.y -= deltaFighting;
  94599. }
  94600. if (gazer._gazeTracker.position.z < 0) {
  94601. gazer._gazeTracker.position.z += deltaFighting;
  94602. }
  94603. else {
  94604. gazer._gazeTracker.position.z -= deltaFighting;
  94605. }
  94606. }
  94607. // Changing the size of the laser pointer based on the distance from the targetted point
  94608. gazer._updatePointerDistance(hit.distance);
  94609. }
  94610. else {
  94611. gazer._updatePointerDistance();
  94612. gazer._gazeTracker.isVisible = false;
  94613. }
  94614. if (hit && hit.pickedMesh) {
  94615. // The object selected is the floor, we're in a teleportation scenario
  94616. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  94617. // Moving the teleportation area to this targetted point
  94618. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  94619. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  94620. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94621. }
  94622. gazer._currentMeshSelected = null;
  94623. if (gazer._teleportationRequestInitiated) {
  94624. this._moveTeleportationSelectorTo(hit, gazer, ray);
  94625. }
  94626. return;
  94627. }
  94628. // If not, we're in a selection scenario
  94629. //this._teleportationAllowed = false;
  94630. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  94631. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  94632. this.onNewMeshPicked.notifyObservers(hit);
  94633. gazer._currentMeshSelected = hit.pickedMesh;
  94634. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  94635. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  94636. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  94637. gazer._isActionableMesh = true;
  94638. }
  94639. else {
  94640. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94641. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94642. gazer._isActionableMesh = false;
  94643. }
  94644. try {
  94645. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  94646. }
  94647. catch (err) {
  94648. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  94649. }
  94650. }
  94651. else {
  94652. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94653. gazer._currentMeshSelected = null;
  94654. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94655. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94656. }
  94657. }
  94658. }
  94659. else {
  94660. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94661. gazer._currentMeshSelected = null;
  94662. //this._teleportationAllowed = false;
  94663. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94664. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94665. }
  94666. };
  94667. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  94668. if (mesh) {
  94669. this.onSelectedMeshUnselected.notifyObservers(mesh);
  94670. }
  94671. };
  94672. /**
  94673. * Sets the color of the laser ray from the vr controllers.
  94674. * @param color new color for the ray.
  94675. */
  94676. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  94677. if (this.leftController) {
  94678. this.leftController._setLaserPointerColor(color);
  94679. }
  94680. if (this.rightController) {
  94681. this.rightController._setLaserPointerColor(color);
  94682. }
  94683. };
  94684. /**
  94685. * Sets the color of the ray from the vr headsets gaze.
  94686. * @param color new color for the ray.
  94687. */
  94688. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  94689. if (!this._cameraGazer._gazeTracker.material) {
  94690. return;
  94691. }
  94692. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  94693. if (this.leftController) {
  94694. this.leftController._gazeTracker.material.emissiveColor = color;
  94695. }
  94696. if (this.rightController) {
  94697. this.rightController._gazeTracker.material.emissiveColor = color;
  94698. }
  94699. };
  94700. /**
  94701. * Exits VR and disposes of the vr experience helper
  94702. */
  94703. VRExperienceHelper.prototype.dispose = function () {
  94704. if (this.isInVRMode) {
  94705. this.exitVR();
  94706. }
  94707. if (this._postProcessMove) {
  94708. this._postProcessMove.dispose();
  94709. }
  94710. if (this._webVRCamera) {
  94711. this._webVRCamera.dispose();
  94712. }
  94713. if (this._vrDeviceOrientationCamera) {
  94714. this._vrDeviceOrientationCamera.dispose();
  94715. }
  94716. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  94717. document.body.removeChild(this._btnVR);
  94718. }
  94719. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  94720. this._deviceOrientationCamera.dispose();
  94721. }
  94722. if (this._cameraGazer) {
  94723. this._cameraGazer.dispose();
  94724. }
  94725. if (this.leftController) {
  94726. this.leftController.dispose();
  94727. }
  94728. if (this.rightController) {
  94729. this.rightController.dispose();
  94730. }
  94731. if (this._teleportationTarget) {
  94732. this._teleportationTarget.dispose();
  94733. }
  94734. this._floorMeshesCollection = [];
  94735. document.removeEventListener("keydown", this._onKeyDown);
  94736. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94737. window.removeEventListener("resize", this._onResize);
  94738. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  94739. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  94740. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  94741. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  94742. document.onmsfullscreenchange = null;
  94743. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  94744. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  94745. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  94746. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94747. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  94748. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  94749. this._scene.unregisterBeforeRender(this.beforeRender);
  94750. };
  94751. /**
  94752. * Gets the name of the VRExperienceHelper class
  94753. * @returns "VRExperienceHelper"
  94754. */
  94755. VRExperienceHelper.prototype.getClassName = function () {
  94756. return "VRExperienceHelper";
  94757. };
  94758. return VRExperienceHelper;
  94759. }());
  94760. BABYLON.VRExperienceHelper = VRExperienceHelper;
  94761. })(BABYLON || (BABYLON = {}));
  94762. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  94763. // Mainly based on these 2 articles :
  94764. // 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
  94765. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  94766. var BABYLON;
  94767. (function (BABYLON) {
  94768. /**
  94769. * Defines the potential axis of a Joystick
  94770. */
  94771. var JoystickAxis;
  94772. (function (JoystickAxis) {
  94773. /** X axis */
  94774. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  94775. /** Y axis */
  94776. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  94777. /** Z axis */
  94778. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  94779. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  94780. /**
  94781. * Class used to define virtual joystick (used in touch mode)
  94782. */
  94783. var VirtualJoystick = /** @class */ (function () {
  94784. /**
  94785. * Creates a new virtual joystick
  94786. * @param leftJoystick defines that the joystick is for left hand (false by default)
  94787. */
  94788. function VirtualJoystick(leftJoystick) {
  94789. var _this = this;
  94790. if (leftJoystick) {
  94791. this._leftJoystick = true;
  94792. }
  94793. else {
  94794. this._leftJoystick = false;
  94795. }
  94796. VirtualJoystick._globalJoystickIndex++;
  94797. // By default left & right arrow keys are moving the X
  94798. // and up & down keys are moving the Y
  94799. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94800. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94801. this.reverseLeftRight = false;
  94802. this.reverseUpDown = false;
  94803. // collections of pointers
  94804. this._touches = new BABYLON.StringDictionary();
  94805. this.deltaPosition = BABYLON.Vector3.Zero();
  94806. this._joystickSensibility = 25;
  94807. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94808. this._onResize = function (evt) {
  94809. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94810. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94811. if (VirtualJoystick.vjCanvas) {
  94812. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  94813. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  94814. }
  94815. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  94816. };
  94817. // injecting a canvas element on top of the canvas 3D game
  94818. if (!VirtualJoystick.vjCanvas) {
  94819. window.addEventListener("resize", this._onResize, false);
  94820. VirtualJoystick.vjCanvas = document.createElement("canvas");
  94821. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94822. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94823. VirtualJoystick.vjCanvas.width = window.innerWidth;
  94824. VirtualJoystick.vjCanvas.height = window.innerHeight;
  94825. VirtualJoystick.vjCanvas.style.width = "100%";
  94826. VirtualJoystick.vjCanvas.style.height = "100%";
  94827. VirtualJoystick.vjCanvas.style.position = "absolute";
  94828. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  94829. VirtualJoystick.vjCanvas.style.top = "0px";
  94830. VirtualJoystick.vjCanvas.style.left = "0px";
  94831. VirtualJoystick.vjCanvas.style.zIndex = "5";
  94832. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  94833. // Support for jQuery PEP polyfill
  94834. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  94835. var context = VirtualJoystick.vjCanvas.getContext('2d');
  94836. if (!context) {
  94837. throw new Error("Unable to create canvas for virtual joystick");
  94838. }
  94839. VirtualJoystick.vjCanvasContext = context;
  94840. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  94841. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94842. document.body.appendChild(VirtualJoystick.vjCanvas);
  94843. }
  94844. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  94845. this.pressed = false;
  94846. // default joystick color
  94847. this._joystickColor = "cyan";
  94848. this._joystickPointerID = -1;
  94849. // current joystick position
  94850. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  94851. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  94852. // origin joystick position
  94853. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  94854. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  94855. this._onPointerDownHandlerRef = function (evt) {
  94856. _this._onPointerDown(evt);
  94857. };
  94858. this._onPointerMoveHandlerRef = function (evt) {
  94859. _this._onPointerMove(evt);
  94860. };
  94861. this._onPointerUpHandlerRef = function (evt) {
  94862. _this._onPointerUp(evt);
  94863. };
  94864. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  94865. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  94866. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  94867. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  94868. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  94869. evt.preventDefault(); // Disables system menu
  94870. }, false);
  94871. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94872. }
  94873. /**
  94874. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  94875. * @param newJoystickSensibility defines the new sensibility
  94876. */
  94877. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  94878. this._joystickSensibility = newJoystickSensibility;
  94879. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94880. };
  94881. VirtualJoystick.prototype._onPointerDown = function (e) {
  94882. var positionOnScreenCondition;
  94883. e.preventDefault();
  94884. if (this._leftJoystick === true) {
  94885. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  94886. }
  94887. else {
  94888. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  94889. }
  94890. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  94891. // First contact will be dedicated to the virtual joystick
  94892. this._joystickPointerID = e.pointerId;
  94893. this._joystickPointerStartPos.x = e.clientX;
  94894. this._joystickPointerStartPos.y = e.clientY;
  94895. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  94896. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  94897. this._deltaJoystickVector.x = 0;
  94898. this._deltaJoystickVector.y = 0;
  94899. this.pressed = true;
  94900. this._touches.add(e.pointerId.toString(), e);
  94901. }
  94902. else {
  94903. // You can only trigger the action buttons with a joystick declared
  94904. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  94905. this._action();
  94906. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  94907. }
  94908. }
  94909. };
  94910. VirtualJoystick.prototype._onPointerMove = function (e) {
  94911. // If the current pointer is the one associated to the joystick (first touch contact)
  94912. if (this._joystickPointerID == e.pointerId) {
  94913. this._joystickPointerPos.x = e.clientX;
  94914. this._joystickPointerPos.y = e.clientY;
  94915. this._deltaJoystickVector = this._joystickPointerPos.clone();
  94916. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  94917. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  94918. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  94919. switch (this._axisTargetedByLeftAndRight) {
  94920. case JoystickAxis.X:
  94921. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  94922. break;
  94923. case JoystickAxis.Y:
  94924. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  94925. break;
  94926. case JoystickAxis.Z:
  94927. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  94928. break;
  94929. }
  94930. var directionUpDown = this.reverseUpDown ? 1 : -1;
  94931. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  94932. switch (this._axisTargetedByUpAndDown) {
  94933. case JoystickAxis.X:
  94934. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  94935. break;
  94936. case JoystickAxis.Y:
  94937. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  94938. break;
  94939. case JoystickAxis.Z:
  94940. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  94941. break;
  94942. }
  94943. }
  94944. else {
  94945. var data = this._touches.get(e.pointerId.toString());
  94946. if (data) {
  94947. data.x = e.clientX;
  94948. data.y = e.clientY;
  94949. }
  94950. }
  94951. };
  94952. VirtualJoystick.prototype._onPointerUp = function (e) {
  94953. if (this._joystickPointerID == e.pointerId) {
  94954. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  94955. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  94956. this._joystickPointerID = -1;
  94957. this.pressed = false;
  94958. }
  94959. else {
  94960. var touch = this._touches.get(e.pointerId.toString());
  94961. if (touch) {
  94962. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94963. }
  94964. }
  94965. this._deltaJoystickVector.x = 0;
  94966. this._deltaJoystickVector.y = 0;
  94967. this._touches.remove(e.pointerId.toString());
  94968. };
  94969. /**
  94970. * Change the color of the virtual joystick
  94971. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  94972. */
  94973. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  94974. this._joystickColor = newColor;
  94975. };
  94976. /**
  94977. * Defines a callback to call when the joystick is touched
  94978. * @param action defines the callback
  94979. */
  94980. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  94981. this._action = action;
  94982. };
  94983. /**
  94984. * Defines which axis you'd like to control for left & right
  94985. * @param axis defines the axis to use
  94986. */
  94987. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  94988. switch (axis) {
  94989. case JoystickAxis.X:
  94990. case JoystickAxis.Y:
  94991. case JoystickAxis.Z:
  94992. this._axisTargetedByLeftAndRight = axis;
  94993. break;
  94994. default:
  94995. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94996. break;
  94997. }
  94998. };
  94999. /**
  95000. * Defines which axis you'd like to control for up & down
  95001. * @param axis defines the axis to use
  95002. */
  95003. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  95004. switch (axis) {
  95005. case JoystickAxis.X:
  95006. case JoystickAxis.Y:
  95007. case JoystickAxis.Z:
  95008. this._axisTargetedByUpAndDown = axis;
  95009. break;
  95010. default:
  95011. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  95012. break;
  95013. }
  95014. };
  95015. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  95016. var _this = this;
  95017. if (this.pressed) {
  95018. this._touches.forEach(function (key, touch) {
  95019. if (touch.pointerId === _this._joystickPointerID) {
  95020. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  95021. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  95022. VirtualJoystick.vjCanvasContext.beginPath();
  95023. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95024. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95025. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  95026. VirtualJoystick.vjCanvasContext.stroke();
  95027. VirtualJoystick.vjCanvasContext.closePath();
  95028. VirtualJoystick.vjCanvasContext.beginPath();
  95029. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95030. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  95031. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  95032. VirtualJoystick.vjCanvasContext.stroke();
  95033. VirtualJoystick.vjCanvasContext.closePath();
  95034. VirtualJoystick.vjCanvasContext.beginPath();
  95035. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95036. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  95037. VirtualJoystick.vjCanvasContext.stroke();
  95038. VirtualJoystick.vjCanvasContext.closePath();
  95039. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  95040. }
  95041. else {
  95042. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  95043. VirtualJoystick.vjCanvasContext.beginPath();
  95044. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  95045. VirtualJoystick.vjCanvasContext.beginPath();
  95046. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  95047. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95048. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  95049. VirtualJoystick.vjCanvasContext.stroke();
  95050. VirtualJoystick.vjCanvasContext.closePath();
  95051. touch.prevX = touch.x;
  95052. touch.prevY = touch.y;
  95053. }
  95054. ;
  95055. });
  95056. }
  95057. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  95058. };
  95059. /**
  95060. * Release internal HTML canvas
  95061. */
  95062. VirtualJoystick.prototype.releaseCanvas = function () {
  95063. if (VirtualJoystick.vjCanvas) {
  95064. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  95065. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  95066. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  95067. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  95068. window.removeEventListener("resize", this._onResize);
  95069. document.body.removeChild(VirtualJoystick.vjCanvas);
  95070. VirtualJoystick.vjCanvas = null;
  95071. }
  95072. };
  95073. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  95074. VirtualJoystick._globalJoystickIndex = 0;
  95075. return VirtualJoystick;
  95076. }());
  95077. BABYLON.VirtualJoystick = VirtualJoystick;
  95078. })(BABYLON || (BABYLON = {}));
  95079. //# sourceMappingURL=babylon.virtualJoystick.js.map
  95080. var BABYLON;
  95081. (function (BABYLON) {
  95082. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  95083. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  95084. });
  95085. // We're mainly based on the logic defined into the FreeCamera code
  95086. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  95087. __extends(VirtualJoysticksCamera, _super);
  95088. function VirtualJoysticksCamera(name, position, scene) {
  95089. var _this = _super.call(this, name, position, scene) || this;
  95090. _this.inputs.addVirtualJoystick();
  95091. return _this;
  95092. }
  95093. VirtualJoysticksCamera.prototype.getClassName = function () {
  95094. return "VirtualJoysticksCamera";
  95095. };
  95096. return VirtualJoysticksCamera;
  95097. }(BABYLON.FreeCamera));
  95098. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  95099. })(BABYLON || (BABYLON = {}));
  95100. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  95101. var BABYLON;
  95102. (function (BABYLON) {
  95103. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  95104. function FreeCameraVirtualJoystickInput() {
  95105. }
  95106. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  95107. return this._leftjoystick;
  95108. };
  95109. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  95110. return this._rightjoystick;
  95111. };
  95112. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  95113. if (this._leftjoystick) {
  95114. var camera = this.camera;
  95115. var speed = camera._computeLocalCameraSpeed() * 50;
  95116. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  95117. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  95118. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  95119. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  95120. if (!this._leftjoystick.pressed) {
  95121. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  95122. }
  95123. if (!this._rightjoystick.pressed) {
  95124. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  95125. }
  95126. }
  95127. };
  95128. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  95129. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  95130. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  95131. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  95132. this._leftjoystick.setJoystickSensibility(0.15);
  95133. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  95134. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  95135. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  95136. this._rightjoystick.reverseUpDown = true;
  95137. this._rightjoystick.setJoystickSensibility(0.05);
  95138. this._rightjoystick.setJoystickColor("yellow");
  95139. };
  95140. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  95141. this._leftjoystick.releaseCanvas();
  95142. this._rightjoystick.releaseCanvas();
  95143. };
  95144. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  95145. return "FreeCameraVirtualJoystickInput";
  95146. };
  95147. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  95148. return "virtualJoystick";
  95149. };
  95150. return FreeCameraVirtualJoystickInput;
  95151. }());
  95152. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  95153. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  95154. })(BABYLON || (BABYLON = {}));
  95155. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  95156. var BABYLON;
  95157. (function (BABYLON) {
  95158. var SimplificationSettings = /** @class */ (function () {
  95159. function SimplificationSettings(quality, distance, optimizeMesh) {
  95160. this.quality = quality;
  95161. this.distance = distance;
  95162. this.optimizeMesh = optimizeMesh;
  95163. }
  95164. return SimplificationSettings;
  95165. }());
  95166. BABYLON.SimplificationSettings = SimplificationSettings;
  95167. var SimplificationQueue = /** @class */ (function () {
  95168. function SimplificationQueue() {
  95169. this.running = false;
  95170. this._simplificationArray = [];
  95171. }
  95172. SimplificationQueue.prototype.addTask = function (task) {
  95173. this._simplificationArray.push(task);
  95174. };
  95175. SimplificationQueue.prototype.executeNext = function () {
  95176. var task = this._simplificationArray.pop();
  95177. if (task) {
  95178. this.running = true;
  95179. this.runSimplification(task);
  95180. }
  95181. else {
  95182. this.running = false;
  95183. }
  95184. };
  95185. SimplificationQueue.prototype.runSimplification = function (task) {
  95186. var _this = this;
  95187. if (task.parallelProcessing) {
  95188. //parallel simplifier
  95189. task.settings.forEach(function (setting) {
  95190. var simplifier = _this.getSimplifier(task);
  95191. simplifier.simplify(setting, function (newMesh) {
  95192. task.mesh.addLODLevel(setting.distance, newMesh);
  95193. newMesh.isVisible = true;
  95194. //check if it is the last
  95195. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  95196. //all done, run the success callback.
  95197. task.successCallback();
  95198. }
  95199. _this.executeNext();
  95200. });
  95201. });
  95202. }
  95203. else {
  95204. //single simplifier.
  95205. var simplifier = this.getSimplifier(task);
  95206. var runDecimation = function (setting, callback) {
  95207. simplifier.simplify(setting, function (newMesh) {
  95208. task.mesh.addLODLevel(setting.distance, newMesh);
  95209. newMesh.isVisible = true;
  95210. //run the next quality level
  95211. callback();
  95212. });
  95213. };
  95214. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  95215. runDecimation(task.settings[loop.index], function () {
  95216. loop.executeNext();
  95217. });
  95218. }, function () {
  95219. //execution ended, run the success callback.
  95220. if (task.successCallback) {
  95221. task.successCallback();
  95222. }
  95223. _this.executeNext();
  95224. });
  95225. }
  95226. };
  95227. SimplificationQueue.prototype.getSimplifier = function (task) {
  95228. switch (task.simplificationType) {
  95229. case SimplificationType.QUADRATIC:
  95230. default:
  95231. return new QuadraticErrorSimplification(task.mesh);
  95232. }
  95233. };
  95234. return SimplificationQueue;
  95235. }());
  95236. BABYLON.SimplificationQueue = SimplificationQueue;
  95237. /**
  95238. * The implemented types of simplification
  95239. * At the moment only Quadratic Error Decimation is implemented
  95240. */
  95241. var SimplificationType;
  95242. (function (SimplificationType) {
  95243. /** Quadratic error decimation */
  95244. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  95245. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  95246. var DecimationTriangle = /** @class */ (function () {
  95247. function DecimationTriangle(vertices) {
  95248. this.vertices = vertices;
  95249. this.error = new Array(4);
  95250. this.deleted = false;
  95251. this.isDirty = false;
  95252. this.deletePending = false;
  95253. this.borderFactor = 0;
  95254. }
  95255. return DecimationTriangle;
  95256. }());
  95257. BABYLON.DecimationTriangle = DecimationTriangle;
  95258. var DecimationVertex = /** @class */ (function () {
  95259. function DecimationVertex(position, id) {
  95260. this.position = position;
  95261. this.id = id;
  95262. this.isBorder = true;
  95263. this.q = new QuadraticMatrix();
  95264. this.triangleCount = 0;
  95265. this.triangleStart = 0;
  95266. this.originalOffsets = [];
  95267. }
  95268. DecimationVertex.prototype.updatePosition = function (newPosition) {
  95269. this.position.copyFrom(newPosition);
  95270. };
  95271. return DecimationVertex;
  95272. }());
  95273. BABYLON.DecimationVertex = DecimationVertex;
  95274. var QuadraticMatrix = /** @class */ (function () {
  95275. function QuadraticMatrix(data) {
  95276. this.data = new Array(10);
  95277. for (var i = 0; i < 10; ++i) {
  95278. if (data && data[i]) {
  95279. this.data[i] = data[i];
  95280. }
  95281. else {
  95282. this.data[i] = 0;
  95283. }
  95284. }
  95285. }
  95286. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  95287. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  95288. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  95289. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  95290. return det;
  95291. };
  95292. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  95293. for (var i = 0; i < 10; ++i) {
  95294. this.data[i] += matrix.data[i];
  95295. }
  95296. };
  95297. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  95298. for (var i = 0; i < 10; ++i) {
  95299. this.data[i] += data[i];
  95300. }
  95301. };
  95302. QuadraticMatrix.prototype.add = function (matrix) {
  95303. var m = new QuadraticMatrix();
  95304. for (var i = 0; i < 10; ++i) {
  95305. m.data[i] = this.data[i] + matrix.data[i];
  95306. }
  95307. return m;
  95308. };
  95309. QuadraticMatrix.FromData = function (a, b, c, d) {
  95310. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  95311. };
  95312. //returning an array to avoid garbage collection
  95313. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  95314. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  95315. };
  95316. return QuadraticMatrix;
  95317. }());
  95318. BABYLON.QuadraticMatrix = QuadraticMatrix;
  95319. var Reference = /** @class */ (function () {
  95320. function Reference(vertexId, triangleId) {
  95321. this.vertexId = vertexId;
  95322. this.triangleId = triangleId;
  95323. }
  95324. return Reference;
  95325. }());
  95326. BABYLON.Reference = Reference;
  95327. /**
  95328. * An implementation of the Quadratic Error simplification algorithm.
  95329. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  95330. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  95331. * @author RaananW
  95332. */
  95333. var QuadraticErrorSimplification = /** @class */ (function () {
  95334. function QuadraticErrorSimplification(_mesh) {
  95335. this._mesh = _mesh;
  95336. this.syncIterations = 5000;
  95337. this.aggressiveness = 7;
  95338. this.decimationIterations = 100;
  95339. this.boundingBoxEpsilon = BABYLON.Epsilon;
  95340. }
  95341. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  95342. var _this = this;
  95343. this.initDecimatedMesh();
  95344. //iterating through the submeshes array, one after the other.
  95345. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  95346. _this.initWithMesh(loop.index, function () {
  95347. _this.runDecimation(settings, loop.index, function () {
  95348. loop.executeNext();
  95349. });
  95350. }, settings.optimizeMesh);
  95351. }, function () {
  95352. setTimeout(function () {
  95353. successCallback(_this._reconstructedMesh);
  95354. }, 0);
  95355. });
  95356. };
  95357. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  95358. var _this = this;
  95359. var targetCount = ~~(this.triangles.length * settings.quality);
  95360. var deletedTriangles = 0;
  95361. var triangleCount = this.triangles.length;
  95362. var iterationFunction = function (iteration, callback) {
  95363. setTimeout(function () {
  95364. if (iteration % 5 === 0) {
  95365. _this.updateMesh(iteration === 0);
  95366. }
  95367. for (var i = 0; i < _this.triangles.length; ++i) {
  95368. _this.triangles[i].isDirty = false;
  95369. }
  95370. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  95371. var trianglesIterator = function (i) {
  95372. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  95373. var t = _this.triangles[tIdx];
  95374. if (!t)
  95375. return;
  95376. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  95377. return;
  95378. }
  95379. for (var j = 0; j < 3; ++j) {
  95380. if (t.error[j] < threshold) {
  95381. var deleted0 = [];
  95382. var deleted1 = [];
  95383. var v0 = t.vertices[j];
  95384. var v1 = t.vertices[(j + 1) % 3];
  95385. if (v0.isBorder || v1.isBorder)
  95386. continue;
  95387. var p = BABYLON.Vector3.Zero();
  95388. var n = BABYLON.Vector3.Zero();
  95389. var uv = BABYLON.Vector2.Zero();
  95390. var color = new BABYLON.Color4(0, 0, 0, 1);
  95391. _this.calculateError(v0, v1, p, n, uv, color);
  95392. var delTr = new Array();
  95393. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  95394. continue;
  95395. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  95396. continue;
  95397. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  95398. continue;
  95399. var uniqueArray = new Array();
  95400. delTr.forEach(function (deletedT) {
  95401. if (uniqueArray.indexOf(deletedT) === -1) {
  95402. deletedT.deletePending = true;
  95403. uniqueArray.push(deletedT);
  95404. }
  95405. });
  95406. if (uniqueArray.length % 2 !== 0) {
  95407. continue;
  95408. }
  95409. v0.q = v1.q.add(v0.q);
  95410. v0.updatePosition(p);
  95411. var tStart = _this.references.length;
  95412. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  95413. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  95414. var tCount = _this.references.length - tStart;
  95415. if (tCount <= v0.triangleCount) {
  95416. if (tCount) {
  95417. for (var c = 0; c < tCount; c++) {
  95418. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  95419. }
  95420. }
  95421. }
  95422. else {
  95423. v0.triangleStart = tStart;
  95424. }
  95425. v0.triangleCount = tCount;
  95426. break;
  95427. }
  95428. }
  95429. };
  95430. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  95431. }, 0);
  95432. };
  95433. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  95434. if (triangleCount - deletedTriangles <= targetCount)
  95435. loop.breakLoop();
  95436. else {
  95437. iterationFunction(loop.index, function () {
  95438. loop.executeNext();
  95439. });
  95440. }
  95441. }, function () {
  95442. setTimeout(function () {
  95443. //reconstruct this part of the mesh
  95444. _this.reconstructMesh(submeshIndex);
  95445. successCallback();
  95446. }, 0);
  95447. });
  95448. };
  95449. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  95450. var _this = this;
  95451. this.vertices = [];
  95452. this.triangles = [];
  95453. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95454. var indices = this._mesh.getIndices();
  95455. var submesh = this._mesh.subMeshes[submeshIndex];
  95456. var findInVertices = function (positionToSearch) {
  95457. if (optimizeMesh) {
  95458. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  95459. if (_this.vertices[ii].position.equals(positionToSearch)) {
  95460. return _this.vertices[ii];
  95461. }
  95462. }
  95463. }
  95464. return null;
  95465. };
  95466. var vertexReferences = [];
  95467. var vertexInit = function (i) {
  95468. if (!positionData) {
  95469. return;
  95470. }
  95471. var offset = i + submesh.verticesStart;
  95472. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  95473. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  95474. vertex.originalOffsets.push(offset);
  95475. if (vertex.id === _this.vertices.length) {
  95476. _this.vertices.push(vertex);
  95477. }
  95478. vertexReferences.push(vertex.id);
  95479. };
  95480. //var totalVertices = mesh.getTotalVertices();
  95481. var totalVertices = submesh.verticesCount;
  95482. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  95483. var indicesInit = function (i) {
  95484. if (!indices) {
  95485. return;
  95486. }
  95487. var offset = (submesh.indexStart / 3) + i;
  95488. var pos = (offset * 3);
  95489. var i0 = indices[pos + 0];
  95490. var i1 = indices[pos + 1];
  95491. var i2 = indices[pos + 2];
  95492. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  95493. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  95494. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  95495. var triangle = new DecimationTriangle([v0, v1, v2]);
  95496. triangle.originalOffset = pos;
  95497. _this.triangles.push(triangle);
  95498. };
  95499. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  95500. _this.init(callback);
  95501. });
  95502. });
  95503. };
  95504. QuadraticErrorSimplification.prototype.init = function (callback) {
  95505. var _this = this;
  95506. var triangleInit1 = function (i) {
  95507. var t = _this.triangles[i];
  95508. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  95509. for (var j = 0; j < 3; j++) {
  95510. 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))));
  95511. }
  95512. };
  95513. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  95514. var triangleInit2 = function (i) {
  95515. var t = _this.triangles[i];
  95516. for (var j = 0; j < 3; ++j) {
  95517. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  95518. }
  95519. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95520. };
  95521. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  95522. callback();
  95523. });
  95524. });
  95525. };
  95526. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  95527. var newTriangles = [];
  95528. var i;
  95529. for (i = 0; i < this.vertices.length; ++i) {
  95530. this.vertices[i].triangleCount = 0;
  95531. }
  95532. var t;
  95533. var j;
  95534. for (i = 0; i < this.triangles.length; ++i) {
  95535. if (!this.triangles[i].deleted) {
  95536. t = this.triangles[i];
  95537. for (j = 0; j < 3; ++j) {
  95538. t.vertices[j].triangleCount = 1;
  95539. }
  95540. newTriangles.push(t);
  95541. }
  95542. }
  95543. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  95544. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  95545. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  95546. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  95547. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  95548. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  95549. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  95550. var vertexCount = 0;
  95551. for (i = 0; i < this.vertices.length; ++i) {
  95552. var vertex = this.vertices[i];
  95553. vertex.id = vertexCount;
  95554. if (vertex.triangleCount) {
  95555. vertex.originalOffsets.forEach(function (originalOffset) {
  95556. if (!normalData) {
  95557. return;
  95558. }
  95559. newPositionData.push(vertex.position.x);
  95560. newPositionData.push(vertex.position.y);
  95561. newPositionData.push(vertex.position.z);
  95562. newNormalData.push(normalData[originalOffset * 3]);
  95563. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  95564. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  95565. if (uvs && uvs.length) {
  95566. newUVsData.push(uvs[(originalOffset * 2)]);
  95567. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  95568. }
  95569. else if (colorsData && colorsData.length) {
  95570. newColorsData.push(colorsData[(originalOffset * 4)]);
  95571. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  95572. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  95573. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  95574. }
  95575. ++vertexCount;
  95576. });
  95577. }
  95578. }
  95579. var startingIndex = this._reconstructedMesh.getTotalIndices();
  95580. var startingVertex = this._reconstructedMesh.getTotalVertices();
  95581. var submeshesArray = this._reconstructedMesh.subMeshes;
  95582. this._reconstructedMesh.subMeshes = [];
  95583. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  95584. var originalIndices = this._mesh.getIndices();
  95585. for (i = 0; i < newTriangles.length; ++i) {
  95586. t = newTriangles[i]; //now get the new referencing point for each vertex
  95587. [0, 1, 2].forEach(function (idx) {
  95588. var id = originalIndices[t.originalOffset + idx];
  95589. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  95590. if (offset < 0)
  95591. offset = 0;
  95592. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  95593. });
  95594. }
  95595. //overwriting the old vertex buffers and indices.
  95596. this._reconstructedMesh.setIndices(newIndicesArray);
  95597. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  95598. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  95599. if (newUVsData.length > 0)
  95600. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  95601. if (newColorsData.length > 0)
  95602. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  95603. //create submesh
  95604. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  95605. if (submeshIndex > 0) {
  95606. this._reconstructedMesh.subMeshes = [];
  95607. submeshesArray.forEach(function (submesh) {
  95608. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  95609. });
  95610. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  95611. }
  95612. };
  95613. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  95614. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  95615. this._reconstructedMesh.material = this._mesh.material;
  95616. this._reconstructedMesh.parent = this._mesh.parent;
  95617. this._reconstructedMesh.isVisible = false;
  95618. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  95619. };
  95620. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  95621. for (var i = 0; i < vertex1.triangleCount; ++i) {
  95622. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  95623. if (t.deleted)
  95624. continue;
  95625. var s = this.references[vertex1.triangleStart + i].vertexId;
  95626. var v1 = t.vertices[(s + 1) % 3];
  95627. var v2 = t.vertices[(s + 2) % 3];
  95628. if ((v1 === vertex2 || v2 === vertex2)) {
  95629. deletedArray[i] = true;
  95630. delTr.push(t);
  95631. continue;
  95632. }
  95633. var d1 = v1.position.subtract(point);
  95634. d1 = d1.normalize();
  95635. var d2 = v2.position.subtract(point);
  95636. d2 = d2.normalize();
  95637. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  95638. return true;
  95639. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  95640. deletedArray[i] = false;
  95641. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  95642. return true;
  95643. }
  95644. return false;
  95645. };
  95646. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  95647. var newDeleted = deletedTriangles;
  95648. for (var i = 0; i < vertex.triangleCount; ++i) {
  95649. var ref = this.references[vertex.triangleStart + i];
  95650. var t = this.triangles[ref.triangleId];
  95651. if (t.deleted)
  95652. continue;
  95653. if (deletedArray[i] && t.deletePending) {
  95654. t.deleted = true;
  95655. newDeleted++;
  95656. continue;
  95657. }
  95658. t.vertices[ref.vertexId] = origVertex;
  95659. t.isDirty = true;
  95660. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  95661. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  95662. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  95663. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95664. this.references.push(ref);
  95665. }
  95666. return newDeleted;
  95667. };
  95668. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  95669. for (var i = 0; i < this.vertices.length; ++i) {
  95670. var vCount = [];
  95671. var vId = [];
  95672. var v = this.vertices[i];
  95673. var j;
  95674. for (j = 0; j < v.triangleCount; ++j) {
  95675. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  95676. for (var ii = 0; ii < 3; ii++) {
  95677. var ofs = 0;
  95678. var vv = triangle.vertices[ii];
  95679. while (ofs < vCount.length) {
  95680. if (vId[ofs] === vv.id)
  95681. break;
  95682. ++ofs;
  95683. }
  95684. if (ofs === vCount.length) {
  95685. vCount.push(1);
  95686. vId.push(vv.id);
  95687. }
  95688. else {
  95689. vCount[ofs]++;
  95690. }
  95691. }
  95692. }
  95693. for (j = 0; j < vCount.length; ++j) {
  95694. if (vCount[j] === 1) {
  95695. this.vertices[vId[j]].isBorder = true;
  95696. }
  95697. else {
  95698. this.vertices[vId[j]].isBorder = false;
  95699. }
  95700. }
  95701. }
  95702. };
  95703. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  95704. if (identifyBorders === void 0) { identifyBorders = false; }
  95705. var i;
  95706. if (!identifyBorders) {
  95707. var newTrianglesVector = [];
  95708. for (i = 0; i < this.triangles.length; ++i) {
  95709. if (!this.triangles[i].deleted) {
  95710. newTrianglesVector.push(this.triangles[i]);
  95711. }
  95712. }
  95713. this.triangles = newTrianglesVector;
  95714. }
  95715. for (i = 0; i < this.vertices.length; ++i) {
  95716. this.vertices[i].triangleCount = 0;
  95717. this.vertices[i].triangleStart = 0;
  95718. }
  95719. var t;
  95720. var j;
  95721. var v;
  95722. for (i = 0; i < this.triangles.length; ++i) {
  95723. t = this.triangles[i];
  95724. for (j = 0; j < 3; ++j) {
  95725. v = t.vertices[j];
  95726. v.triangleCount++;
  95727. }
  95728. }
  95729. var tStart = 0;
  95730. for (i = 0; i < this.vertices.length; ++i) {
  95731. this.vertices[i].triangleStart = tStart;
  95732. tStart += this.vertices[i].triangleCount;
  95733. this.vertices[i].triangleCount = 0;
  95734. }
  95735. var newReferences = new Array(this.triangles.length * 3);
  95736. for (i = 0; i < this.triangles.length; ++i) {
  95737. t = this.triangles[i];
  95738. for (j = 0; j < 3; ++j) {
  95739. v = t.vertices[j];
  95740. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  95741. v.triangleCount++;
  95742. }
  95743. }
  95744. this.references = newReferences;
  95745. if (identifyBorders) {
  95746. this.identifyBorder();
  95747. }
  95748. };
  95749. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  95750. var x = point.x;
  95751. var y = point.y;
  95752. var z = point.z;
  95753. 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
  95754. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  95755. };
  95756. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  95757. var q = vertex1.q.add(vertex2.q);
  95758. var border = vertex1.isBorder && vertex2.isBorder;
  95759. var error = 0;
  95760. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  95761. if (qDet !== 0 && !border) {
  95762. if (!pointResult) {
  95763. pointResult = BABYLON.Vector3.Zero();
  95764. }
  95765. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  95766. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  95767. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  95768. error = this.vertexError(q, pointResult);
  95769. }
  95770. else {
  95771. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  95772. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  95773. var error1 = this.vertexError(q, vertex1.position);
  95774. var error2 = this.vertexError(q, vertex2.position);
  95775. var error3 = this.vertexError(q, p3);
  95776. error = Math.min(error1, error2, error3);
  95777. if (error === error1) {
  95778. if (pointResult) {
  95779. pointResult.copyFrom(vertex1.position);
  95780. }
  95781. }
  95782. else if (error === error2) {
  95783. if (pointResult) {
  95784. pointResult.copyFrom(vertex2.position);
  95785. }
  95786. }
  95787. else {
  95788. if (pointResult) {
  95789. pointResult.copyFrom(p3);
  95790. }
  95791. }
  95792. }
  95793. return error;
  95794. };
  95795. return QuadraticErrorSimplification;
  95796. }());
  95797. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  95798. })(BABYLON || (BABYLON = {}));
  95799. //# sourceMappingURL=babylon.meshSimplification.js.map
  95800. var BABYLON;
  95801. (function (BABYLON) {
  95802. var MeshLODLevel = /** @class */ (function () {
  95803. function MeshLODLevel(distance, mesh) {
  95804. this.distance = distance;
  95805. this.mesh = mesh;
  95806. }
  95807. return MeshLODLevel;
  95808. }());
  95809. BABYLON.MeshLODLevel = MeshLODLevel;
  95810. })(BABYLON || (BABYLON = {}));
  95811. //# sourceMappingURL=babylon.meshLODLevel.js.map
  95812. var BABYLON;
  95813. (function (BABYLON) {
  95814. /**
  95815. * Defines the root class used to create scene optimization to use with SceneOptimizer
  95816. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95817. */
  95818. var SceneOptimization = /** @class */ (function () {
  95819. /**
  95820. * Creates the SceneOptimization object
  95821. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95822. * @param desc defines the description associated with the optimization
  95823. */
  95824. function SceneOptimization(
  95825. /**
  95826. * Defines the priority of this optimization (0 by default which means first in the list)
  95827. */
  95828. priority) {
  95829. if (priority === void 0) { priority = 0; }
  95830. this.priority = priority;
  95831. }
  95832. /**
  95833. * Gets a string describing the action executed by the current optimization
  95834. * @returns description string
  95835. */
  95836. SceneOptimization.prototype.getDescription = function () {
  95837. return "";
  95838. };
  95839. /**
  95840. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95841. * @param scene defines the current scene where to apply this optimization
  95842. * @param optimizer defines the current optimizer
  95843. * @returns true if everything that can be done was applied
  95844. */
  95845. SceneOptimization.prototype.apply = function (scene, optimizer) {
  95846. return true;
  95847. };
  95848. ;
  95849. return SceneOptimization;
  95850. }());
  95851. BABYLON.SceneOptimization = SceneOptimization;
  95852. /**
  95853. * Defines an optimization used to reduce the size of render target textures
  95854. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95855. */
  95856. var TextureOptimization = /** @class */ (function (_super) {
  95857. __extends(TextureOptimization, _super);
  95858. /**
  95859. * Creates the TextureOptimization object
  95860. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95861. * @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
  95862. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95863. */
  95864. function TextureOptimization(
  95865. /**
  95866. * Defines the priority of this optimization (0 by default which means first in the list)
  95867. */
  95868. priority,
  95869. /**
  95870. * 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
  95871. */
  95872. maximumSize,
  95873. /**
  95874. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95875. */
  95876. step) {
  95877. if (priority === void 0) { priority = 0; }
  95878. if (maximumSize === void 0) { maximumSize = 1024; }
  95879. if (step === void 0) { step = 0.5; }
  95880. var _this = _super.call(this, priority) || this;
  95881. _this.priority = priority;
  95882. _this.maximumSize = maximumSize;
  95883. _this.step = step;
  95884. return _this;
  95885. }
  95886. /**
  95887. * Gets a string describing the action executed by the current optimization
  95888. * @returns description string
  95889. */
  95890. TextureOptimization.prototype.getDescription = function () {
  95891. return "Reducing render target texture size to " + this.maximumSize;
  95892. };
  95893. /**
  95894. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95895. * @param scene defines the current scene where to apply this optimization
  95896. * @param optimizer defines the current optimizer
  95897. * @returns true if everything that can be done was applied
  95898. */
  95899. TextureOptimization.prototype.apply = function (scene, optimizer) {
  95900. var allDone = true;
  95901. for (var index = 0; index < scene.textures.length; index++) {
  95902. var texture = scene.textures[index];
  95903. if (!texture.canRescale || texture.getContext) {
  95904. continue;
  95905. }
  95906. var currentSize = texture.getSize();
  95907. var maxDimension = Math.max(currentSize.width, currentSize.height);
  95908. if (maxDimension > this.maximumSize) {
  95909. texture.scale(this.step);
  95910. allDone = false;
  95911. }
  95912. }
  95913. return allDone;
  95914. };
  95915. return TextureOptimization;
  95916. }(SceneOptimization));
  95917. BABYLON.TextureOptimization = TextureOptimization;
  95918. /**
  95919. * Defines an optimization used to increase or decrease the rendering resolution
  95920. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95921. */
  95922. var HardwareScalingOptimization = /** @class */ (function (_super) {
  95923. __extends(HardwareScalingOptimization, _super);
  95924. /**
  95925. * Creates the HardwareScalingOptimization object
  95926. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95927. * @param maximumScale defines the maximum scale to use (2 by default)
  95928. * @param step defines the step to use between two passes (0.5 by default)
  95929. */
  95930. function HardwareScalingOptimization(
  95931. /**
  95932. * Defines the priority of this optimization (0 by default which means first in the list)
  95933. */
  95934. priority,
  95935. /**
  95936. * Defines the maximum scale to use (2 by default)
  95937. */
  95938. maximumScale,
  95939. /**
  95940. * Defines the step to use between two passes (0.5 by default)
  95941. */
  95942. step) {
  95943. if (priority === void 0) { priority = 0; }
  95944. if (maximumScale === void 0) { maximumScale = 2; }
  95945. if (step === void 0) { step = 0.25; }
  95946. var _this = _super.call(this, priority) || this;
  95947. _this.priority = priority;
  95948. _this.maximumScale = maximumScale;
  95949. _this.step = step;
  95950. _this._currentScale = -1;
  95951. _this._directionOffset = 1;
  95952. return _this;
  95953. }
  95954. /**
  95955. * Gets a string describing the action executed by the current optimization
  95956. * @return description string
  95957. */
  95958. HardwareScalingOptimization.prototype.getDescription = function () {
  95959. return "Setting hardware scaling level to " + this._currentScale;
  95960. };
  95961. /**
  95962. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95963. * @param scene defines the current scene where to apply this optimization
  95964. * @param optimizer defines the current optimizer
  95965. * @returns true if everything that can be done was applied
  95966. */
  95967. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  95968. if (this._currentScale === -1) {
  95969. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  95970. if (this._currentScale > this.maximumScale) {
  95971. this._directionOffset = -1;
  95972. }
  95973. }
  95974. this._currentScale += this._directionOffset * this.step;
  95975. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  95976. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  95977. };
  95978. ;
  95979. return HardwareScalingOptimization;
  95980. }(SceneOptimization));
  95981. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  95982. /**
  95983. * Defines an optimization used to remove shadows
  95984. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95985. */
  95986. var ShadowsOptimization = /** @class */ (function (_super) {
  95987. __extends(ShadowsOptimization, _super);
  95988. function ShadowsOptimization() {
  95989. return _super !== null && _super.apply(this, arguments) || this;
  95990. }
  95991. /**
  95992. * Gets a string describing the action executed by the current optimization
  95993. * @return description string
  95994. */
  95995. ShadowsOptimization.prototype.getDescription = function () {
  95996. return "Turning shadows on/off";
  95997. };
  95998. /**
  95999. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96000. * @param scene defines the current scene where to apply this optimization
  96001. * @param optimizer defines the current optimizer
  96002. * @returns true if everything that can be done was applied
  96003. */
  96004. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  96005. scene.shadowsEnabled = optimizer.isInImprovementMode;
  96006. return true;
  96007. };
  96008. ;
  96009. return ShadowsOptimization;
  96010. }(SceneOptimization));
  96011. BABYLON.ShadowsOptimization = ShadowsOptimization;
  96012. /**
  96013. * Defines an optimization used to turn post-processes off
  96014. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96015. */
  96016. var PostProcessesOptimization = /** @class */ (function (_super) {
  96017. __extends(PostProcessesOptimization, _super);
  96018. function PostProcessesOptimization() {
  96019. return _super !== null && _super.apply(this, arguments) || this;
  96020. }
  96021. /**
  96022. * Gets a string describing the action executed by the current optimization
  96023. * @return description string
  96024. */
  96025. PostProcessesOptimization.prototype.getDescription = function () {
  96026. return "Turning post-processes on/off";
  96027. };
  96028. /**
  96029. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96030. * @param scene defines the current scene where to apply this optimization
  96031. * @param optimizer defines the current optimizer
  96032. * @returns true if everything that can be done was applied
  96033. */
  96034. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  96035. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  96036. return true;
  96037. };
  96038. ;
  96039. return PostProcessesOptimization;
  96040. }(SceneOptimization));
  96041. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  96042. /**
  96043. * Defines an optimization used to turn lens flares off
  96044. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96045. */
  96046. var LensFlaresOptimization = /** @class */ (function (_super) {
  96047. __extends(LensFlaresOptimization, _super);
  96048. function LensFlaresOptimization() {
  96049. return _super !== null && _super.apply(this, arguments) || this;
  96050. }
  96051. /**
  96052. * Gets a string describing the action executed by the current optimization
  96053. * @return description string
  96054. */
  96055. LensFlaresOptimization.prototype.getDescription = function () {
  96056. return "Turning lens flares on/off";
  96057. };
  96058. /**
  96059. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96060. * @param scene defines the current scene where to apply this optimization
  96061. * @param optimizer defines the current optimizer
  96062. * @returns true if everything that can be done was applied
  96063. */
  96064. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  96065. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  96066. return true;
  96067. };
  96068. ;
  96069. return LensFlaresOptimization;
  96070. }(SceneOptimization));
  96071. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  96072. /**
  96073. * Defines an optimization based on user defined callback.
  96074. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96075. */
  96076. var CustomOptimization = /** @class */ (function (_super) {
  96077. __extends(CustomOptimization, _super);
  96078. function CustomOptimization() {
  96079. return _super !== null && _super.apply(this, arguments) || this;
  96080. }
  96081. /**
  96082. * Gets a string describing the action executed by the current optimization
  96083. * @returns description string
  96084. */
  96085. CustomOptimization.prototype.getDescription = function () {
  96086. if (this.onGetDescription) {
  96087. return this.onGetDescription();
  96088. }
  96089. return "Running user defined callback";
  96090. };
  96091. /**
  96092. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96093. * @param scene defines the current scene where to apply this optimization
  96094. * @param optimizer defines the current optimizer
  96095. * @returns true if everything that can be done was applied
  96096. */
  96097. CustomOptimization.prototype.apply = function (scene, optimizer) {
  96098. if (this.onApply) {
  96099. return this.onApply(scene, optimizer);
  96100. }
  96101. return true;
  96102. };
  96103. ;
  96104. return CustomOptimization;
  96105. }(SceneOptimization));
  96106. BABYLON.CustomOptimization = CustomOptimization;
  96107. /**
  96108. * Defines an optimization used to turn particles off
  96109. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96110. */
  96111. var ParticlesOptimization = /** @class */ (function (_super) {
  96112. __extends(ParticlesOptimization, _super);
  96113. function ParticlesOptimization() {
  96114. return _super !== null && _super.apply(this, arguments) || this;
  96115. }
  96116. /**
  96117. * Gets a string describing the action executed by the current optimization
  96118. * @return description string
  96119. */
  96120. ParticlesOptimization.prototype.getDescription = function () {
  96121. return "Turning particles on/off";
  96122. };
  96123. /**
  96124. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96125. * @param scene defines the current scene where to apply this optimization
  96126. * @param optimizer defines the current optimizer
  96127. * @returns true if everything that can be done was applied
  96128. */
  96129. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  96130. scene.particlesEnabled = optimizer.isInImprovementMode;
  96131. return true;
  96132. };
  96133. ;
  96134. return ParticlesOptimization;
  96135. }(SceneOptimization));
  96136. BABYLON.ParticlesOptimization = ParticlesOptimization;
  96137. /**
  96138. * Defines an optimization used to turn render targets off
  96139. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96140. */
  96141. var RenderTargetsOptimization = /** @class */ (function (_super) {
  96142. __extends(RenderTargetsOptimization, _super);
  96143. function RenderTargetsOptimization() {
  96144. return _super !== null && _super.apply(this, arguments) || this;
  96145. }
  96146. /**
  96147. * Gets a string describing the action executed by the current optimization
  96148. * @return description string
  96149. */
  96150. RenderTargetsOptimization.prototype.getDescription = function () {
  96151. return "Turning render targets off";
  96152. };
  96153. /**
  96154. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96155. * @param scene defines the current scene where to apply this optimization
  96156. * @param optimizer defines the current optimizer
  96157. * @returns true if everything that can be done was applied
  96158. */
  96159. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  96160. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  96161. return true;
  96162. };
  96163. ;
  96164. return RenderTargetsOptimization;
  96165. }(SceneOptimization));
  96166. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  96167. /**
  96168. * Defines an optimization used to merge meshes with compatible materials
  96169. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96170. */
  96171. var MergeMeshesOptimization = /** @class */ (function (_super) {
  96172. __extends(MergeMeshesOptimization, _super);
  96173. function MergeMeshesOptimization() {
  96174. var _this = _super !== null && _super.apply(this, arguments) || this;
  96175. _this._canBeMerged = function (abstractMesh) {
  96176. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  96177. return false;
  96178. }
  96179. var mesh = abstractMesh;
  96180. if (mesh.isDisposed()) {
  96181. return false;
  96182. }
  96183. if (!mesh.isVisible || !mesh.isEnabled()) {
  96184. return false;
  96185. }
  96186. if (mesh.instances.length > 0) {
  96187. return false;
  96188. }
  96189. if (mesh.skeleton || mesh.hasLODLevels) {
  96190. return false;
  96191. }
  96192. return true;
  96193. };
  96194. return _this;
  96195. }
  96196. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  96197. /**
  96198. * Gets or sets a boolean which defines if optimization octree has to be updated
  96199. */
  96200. get: function () {
  96201. return MergeMeshesOptimization._UpdateSelectionTree;
  96202. },
  96203. /**
  96204. * Gets or sets a boolean which defines if optimization octree has to be updated
  96205. */
  96206. set: function (value) {
  96207. MergeMeshesOptimization._UpdateSelectionTree = value;
  96208. },
  96209. enumerable: true,
  96210. configurable: true
  96211. });
  96212. /**
  96213. * Gets a string describing the action executed by the current optimization
  96214. * @return description string
  96215. */
  96216. MergeMeshesOptimization.prototype.getDescription = function () {
  96217. return "Merging similar meshes together";
  96218. };
  96219. /**
  96220. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96221. * @param scene defines the current scene where to apply this optimization
  96222. * @param optimizer defines the current optimizer
  96223. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  96224. * @returns true if everything that can be done was applied
  96225. */
  96226. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  96227. var globalPool = scene.meshes.slice(0);
  96228. var globalLength = globalPool.length;
  96229. for (var index = 0; index < globalLength; index++) {
  96230. var currentPool = new Array();
  96231. var current = globalPool[index];
  96232. // Checks
  96233. if (!this._canBeMerged(current)) {
  96234. continue;
  96235. }
  96236. currentPool.push(current);
  96237. // Find compatible meshes
  96238. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  96239. var otherMesh = globalPool[subIndex];
  96240. if (!this._canBeMerged(otherMesh)) {
  96241. continue;
  96242. }
  96243. if (otherMesh.material !== current.material) {
  96244. continue;
  96245. }
  96246. if (otherMesh.checkCollisions !== current.checkCollisions) {
  96247. continue;
  96248. }
  96249. currentPool.push(otherMesh);
  96250. globalLength--;
  96251. globalPool.splice(subIndex, 1);
  96252. subIndex--;
  96253. }
  96254. if (currentPool.length < 2) {
  96255. continue;
  96256. }
  96257. // Merge meshes
  96258. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  96259. }
  96260. if (updateSelectionTree != undefined) {
  96261. if (updateSelectionTree) {
  96262. scene.createOrUpdateSelectionOctree();
  96263. }
  96264. }
  96265. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  96266. scene.createOrUpdateSelectionOctree();
  96267. }
  96268. return true;
  96269. };
  96270. ;
  96271. MergeMeshesOptimization._UpdateSelectionTree = false;
  96272. return MergeMeshesOptimization;
  96273. }(SceneOptimization));
  96274. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  96275. /**
  96276. * Defines a list of options used by SceneOptimizer
  96277. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96278. */
  96279. var SceneOptimizerOptions = /** @class */ (function () {
  96280. /**
  96281. * Creates a new list of options used by SceneOptimizer
  96282. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  96283. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  96284. */
  96285. function SceneOptimizerOptions(
  96286. /**
  96287. * Defines the target frame rate to reach (60 by default)
  96288. */
  96289. targetFrameRate,
  96290. /**
  96291. * Defines the interval between two checkes (2000ms by default)
  96292. */
  96293. trackerDuration) {
  96294. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  96295. if (trackerDuration === void 0) { trackerDuration = 2000; }
  96296. this.targetFrameRate = targetFrameRate;
  96297. this.trackerDuration = trackerDuration;
  96298. /**
  96299. * Gets the list of optimizations to apply
  96300. */
  96301. this.optimizations = new Array();
  96302. }
  96303. /**
  96304. * Add a new optimization
  96305. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  96306. * @returns the current SceneOptimizerOptions
  96307. */
  96308. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  96309. this.optimizations.push(optimization);
  96310. return this;
  96311. };
  96312. /**
  96313. * Add a new custom optimization
  96314. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  96315. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  96316. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96317. * @returns the current SceneOptimizerOptions
  96318. */
  96319. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  96320. if (priority === void 0) { priority = 0; }
  96321. var optimization = new CustomOptimization(priority);
  96322. optimization.onApply = onApply;
  96323. optimization.onGetDescription = onGetDescription;
  96324. this.optimizations.push(optimization);
  96325. return this;
  96326. };
  96327. /**
  96328. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  96329. * @param targetFrameRate defines the target frame rate (60 by default)
  96330. * @returns a SceneOptimizerOptions object
  96331. */
  96332. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  96333. var result = new SceneOptimizerOptions(targetFrameRate);
  96334. var priority = 0;
  96335. result.addOptimization(new MergeMeshesOptimization(priority));
  96336. result.addOptimization(new ShadowsOptimization(priority));
  96337. result.addOptimization(new LensFlaresOptimization(priority));
  96338. // Next priority
  96339. priority++;
  96340. result.addOptimization(new PostProcessesOptimization(priority));
  96341. result.addOptimization(new ParticlesOptimization(priority));
  96342. // Next priority
  96343. priority++;
  96344. result.addOptimization(new TextureOptimization(priority, 1024));
  96345. return result;
  96346. };
  96347. /**
  96348. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  96349. * @param targetFrameRate defines the target frame rate (60 by default)
  96350. * @returns a SceneOptimizerOptions object
  96351. */
  96352. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  96353. var result = new SceneOptimizerOptions(targetFrameRate);
  96354. var priority = 0;
  96355. result.addOptimization(new MergeMeshesOptimization(priority));
  96356. result.addOptimization(new ShadowsOptimization(priority));
  96357. result.addOptimization(new LensFlaresOptimization(priority));
  96358. // Next priority
  96359. priority++;
  96360. result.addOptimization(new PostProcessesOptimization(priority));
  96361. result.addOptimization(new ParticlesOptimization(priority));
  96362. // Next priority
  96363. priority++;
  96364. result.addOptimization(new TextureOptimization(priority, 512));
  96365. // Next priority
  96366. priority++;
  96367. result.addOptimization(new RenderTargetsOptimization(priority));
  96368. // Next priority
  96369. priority++;
  96370. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  96371. return result;
  96372. };
  96373. /**
  96374. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  96375. * @param targetFrameRate defines the target frame rate (60 by default)
  96376. * @returns a SceneOptimizerOptions object
  96377. */
  96378. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  96379. var result = new SceneOptimizerOptions(targetFrameRate);
  96380. var priority = 0;
  96381. result.addOptimization(new MergeMeshesOptimization(priority));
  96382. result.addOptimization(new ShadowsOptimization(priority));
  96383. result.addOptimization(new LensFlaresOptimization(priority));
  96384. // Next priority
  96385. priority++;
  96386. result.addOptimization(new PostProcessesOptimization(priority));
  96387. result.addOptimization(new ParticlesOptimization(priority));
  96388. // Next priority
  96389. priority++;
  96390. result.addOptimization(new TextureOptimization(priority, 256));
  96391. // Next priority
  96392. priority++;
  96393. result.addOptimization(new RenderTargetsOptimization(priority));
  96394. // Next priority
  96395. priority++;
  96396. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  96397. return result;
  96398. };
  96399. return SceneOptimizerOptions;
  96400. }());
  96401. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  96402. /**
  96403. * Class used to run optimizations in order to reach a target frame rate
  96404. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96405. */
  96406. var SceneOptimizer = /** @class */ (function () {
  96407. /**
  96408. * Creates a new SceneOptimizer
  96409. * @param scene defines the scene to work on
  96410. * @param options defines the options to use with the SceneOptimizer
  96411. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  96412. * @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)
  96413. */
  96414. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  96415. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  96416. if (improvementMode === void 0) { improvementMode = false; }
  96417. var _this = this;
  96418. this._isRunning = false;
  96419. this._currentPriorityLevel = 0;
  96420. this._targetFrameRate = 60;
  96421. this._trackerDuration = 2000;
  96422. this._currentFrameRate = 0;
  96423. this._improvementMode = false;
  96424. /**
  96425. * Defines an observable called when the optimizer reaches the target frame rate
  96426. */
  96427. this.onSuccessObservable = new BABYLON.Observable();
  96428. /**
  96429. * Defines an observable called when the optimizer enables an optimization
  96430. */
  96431. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  96432. /**
  96433. * Defines an observable called when the optimizer is not able to reach the target frame rate
  96434. */
  96435. this.onFailureObservable = new BABYLON.Observable();
  96436. if (!options) {
  96437. this._options = new SceneOptimizerOptions();
  96438. }
  96439. else {
  96440. this._options = options;
  96441. }
  96442. if (this._options.targetFrameRate) {
  96443. this._targetFrameRate = this._options.targetFrameRate;
  96444. }
  96445. if (this._options.trackerDuration) {
  96446. this._trackerDuration = this._options.trackerDuration;
  96447. }
  96448. if (autoGeneratePriorities) {
  96449. var priority = 0;
  96450. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  96451. var optim = _a[_i];
  96452. optim.priority = priority++;
  96453. }
  96454. }
  96455. this._improvementMode = improvementMode;
  96456. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96457. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  96458. _this._sceneDisposeObserver = null;
  96459. _this.dispose();
  96460. });
  96461. }
  96462. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  96463. /**
  96464. * Gets a boolean indicating if the optimizer is in improvement mode
  96465. */
  96466. get: function () {
  96467. return this._improvementMode;
  96468. },
  96469. enumerable: true,
  96470. configurable: true
  96471. });
  96472. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  96473. /**
  96474. * Gets the current priority level (0 at start)
  96475. */
  96476. get: function () {
  96477. return this._currentPriorityLevel;
  96478. },
  96479. enumerable: true,
  96480. configurable: true
  96481. });
  96482. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  96483. /**
  96484. * Gets the current frame rate checked by the SceneOptimizer
  96485. */
  96486. get: function () {
  96487. return this._currentFrameRate;
  96488. },
  96489. enumerable: true,
  96490. configurable: true
  96491. });
  96492. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  96493. /**
  96494. * Gets or sets the current target frame rate (60 by default)
  96495. */
  96496. get: function () {
  96497. return this._targetFrameRate;
  96498. },
  96499. /**
  96500. * Gets or sets the current target frame rate (60 by default)
  96501. */
  96502. set: function (value) {
  96503. this._targetFrameRate = value;
  96504. },
  96505. enumerable: true,
  96506. configurable: true
  96507. });
  96508. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  96509. /**
  96510. * Gets or sets the current interval between two checks (every 2000ms by default)
  96511. */
  96512. get: function () {
  96513. return this._trackerDuration;
  96514. },
  96515. /**
  96516. * Gets or sets the current interval between two checks (every 2000ms by default)
  96517. */
  96518. set: function (value) {
  96519. this._trackerDuration = value;
  96520. },
  96521. enumerable: true,
  96522. configurable: true
  96523. });
  96524. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  96525. /**
  96526. * Gets the list of active optimizations
  96527. */
  96528. get: function () {
  96529. return this._options.optimizations;
  96530. },
  96531. enumerable: true,
  96532. configurable: true
  96533. });
  96534. /**
  96535. * Stops the current optimizer
  96536. */
  96537. SceneOptimizer.prototype.stop = function () {
  96538. this._isRunning = false;
  96539. };
  96540. /**
  96541. * Reset the optimizer to initial step (current priority level = 0)
  96542. */
  96543. SceneOptimizer.prototype.reset = function () {
  96544. this._currentPriorityLevel = 0;
  96545. };
  96546. /**
  96547. * Start the optimizer. By default it will try to reach a specific framerate
  96548. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  96549. */
  96550. SceneOptimizer.prototype.start = function () {
  96551. var _this = this;
  96552. if (this._isRunning) {
  96553. return;
  96554. }
  96555. this._isRunning = true;
  96556. // Let's wait for the scene to be ready before running our check
  96557. this._scene.executeWhenReady(function () {
  96558. setTimeout(function () {
  96559. _this._checkCurrentState();
  96560. }, _this._trackerDuration);
  96561. });
  96562. };
  96563. SceneOptimizer.prototype._checkCurrentState = function () {
  96564. var _this = this;
  96565. if (!this._isRunning) {
  96566. return;
  96567. }
  96568. var scene = this._scene;
  96569. var options = this._options;
  96570. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  96571. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  96572. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  96573. this._isRunning = false;
  96574. this.onSuccessObservable.notifyObservers(this);
  96575. return;
  96576. }
  96577. // Apply current level of optimizations
  96578. var allDone = true;
  96579. var noOptimizationApplied = true;
  96580. for (var index = 0; index < options.optimizations.length; index++) {
  96581. var optimization = options.optimizations[index];
  96582. if (optimization.priority === this._currentPriorityLevel) {
  96583. noOptimizationApplied = false;
  96584. allDone = allDone && optimization.apply(scene, this);
  96585. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  96586. }
  96587. }
  96588. // If no optimization was applied, this is a failure :(
  96589. if (noOptimizationApplied) {
  96590. this._isRunning = false;
  96591. this.onFailureObservable.notifyObservers(this);
  96592. return;
  96593. }
  96594. // If all optimizations were done, move to next level
  96595. if (allDone) {
  96596. this._currentPriorityLevel++;
  96597. }
  96598. // Let's the system running for a specific amount of time before checking FPS
  96599. scene.executeWhenReady(function () {
  96600. setTimeout(function () {
  96601. _this._checkCurrentState();
  96602. }, _this._trackerDuration);
  96603. });
  96604. };
  96605. /**
  96606. * Release all resources
  96607. */
  96608. SceneOptimizer.prototype.dispose = function () {
  96609. this.stop();
  96610. this.onSuccessObservable.clear();
  96611. this.onFailureObservable.clear();
  96612. this.onNewOptimizationAppliedObservable.clear();
  96613. if (this._sceneDisposeObserver) {
  96614. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  96615. }
  96616. };
  96617. /**
  96618. * Helper function to create a SceneOptimizer with one single line of code
  96619. * @param scene defines the scene to work on
  96620. * @param options defines the options to use with the SceneOptimizer
  96621. * @param onSuccess defines a callback to call on success
  96622. * @param onFailure defines a callback to call on failure
  96623. * @returns the new SceneOptimizer object
  96624. */
  96625. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  96626. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  96627. if (onSuccess) {
  96628. optimizer.onSuccessObservable.add(function () {
  96629. onSuccess();
  96630. });
  96631. }
  96632. if (onFailure) {
  96633. optimizer.onFailureObservable.add(function () {
  96634. onFailure();
  96635. });
  96636. }
  96637. optimizer.start();
  96638. return optimizer;
  96639. };
  96640. return SceneOptimizer;
  96641. }());
  96642. BABYLON.SceneOptimizer = SceneOptimizer;
  96643. })(BABYLON || (BABYLON = {}));
  96644. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  96645. var BABYLON;
  96646. (function (BABYLON) {
  96647. var OutlineRenderer = /** @class */ (function () {
  96648. function OutlineRenderer(scene) {
  96649. this.zOffset = 1;
  96650. this._scene = scene;
  96651. }
  96652. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  96653. var _this = this;
  96654. if (useOverlay === void 0) { useOverlay = false; }
  96655. var scene = this._scene;
  96656. var engine = this._scene.getEngine();
  96657. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96658. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  96659. return;
  96660. }
  96661. var mesh = subMesh.getRenderingMesh();
  96662. var material = subMesh.getMaterial();
  96663. if (!material || !scene.activeCamera) {
  96664. return;
  96665. }
  96666. engine.enableEffect(this._effect);
  96667. // Logarithmic depth
  96668. if (material.useLogarithmicDepth) {
  96669. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  96670. }
  96671. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  96672. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  96673. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  96674. // Bones
  96675. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96676. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96677. }
  96678. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  96679. // Alpha test
  96680. if (material && material.needAlphaTesting()) {
  96681. var alphaTexture = material.getAlphaTestTexture();
  96682. if (alphaTexture) {
  96683. this._effect.setTexture("diffuseSampler", alphaTexture);
  96684. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  96685. }
  96686. }
  96687. engine.setZOffset(-this.zOffset);
  96688. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  96689. engine.setZOffset(0);
  96690. };
  96691. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  96692. var defines = [];
  96693. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  96694. var mesh = subMesh.getMesh();
  96695. var material = subMesh.getMaterial();
  96696. if (material) {
  96697. // Alpha test
  96698. if (material.needAlphaTesting()) {
  96699. defines.push("#define ALPHATEST");
  96700. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96701. attribs.push(BABYLON.VertexBuffer.UVKind);
  96702. defines.push("#define UV1");
  96703. }
  96704. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  96705. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96706. defines.push("#define UV2");
  96707. }
  96708. }
  96709. //Logarithmic depth
  96710. if (material.useLogarithmicDepth) {
  96711. defines.push("#define LOGARITHMICDEPTH");
  96712. }
  96713. }
  96714. // Bones
  96715. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96716. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96717. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96718. if (mesh.numBoneInfluencers > 4) {
  96719. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96720. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96721. }
  96722. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96723. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  96724. }
  96725. else {
  96726. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96727. }
  96728. // Instances
  96729. if (useInstances) {
  96730. defines.push("#define INSTANCES");
  96731. attribs.push("world0");
  96732. attribs.push("world1");
  96733. attribs.push("world2");
  96734. attribs.push("world3");
  96735. }
  96736. // Get correct effect
  96737. var join = defines.join("\n");
  96738. if (this._cachedDefines !== join) {
  96739. this._cachedDefines = join;
  96740. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  96741. }
  96742. return this._effect.isReady();
  96743. };
  96744. return OutlineRenderer;
  96745. }());
  96746. BABYLON.OutlineRenderer = OutlineRenderer;
  96747. })(BABYLON || (BABYLON = {}));
  96748. //# sourceMappingURL=babylon.outlineRenderer.js.map
  96749. var BABYLON;
  96750. (function (BABYLON) {
  96751. var FaceAdjacencies = /** @class */ (function () {
  96752. function FaceAdjacencies() {
  96753. this.edges = new Array();
  96754. this.edgesConnectedCount = 0;
  96755. }
  96756. return FaceAdjacencies;
  96757. }());
  96758. var EdgesRenderer = /** @class */ (function () {
  96759. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  96760. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  96761. if (epsilon === void 0) { epsilon = 0.95; }
  96762. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  96763. this.edgesWidthScalerForOrthographic = 1000.0;
  96764. this.edgesWidthScalerForPerspective = 50.0;
  96765. this._linesPositions = new Array();
  96766. this._linesNormals = new Array();
  96767. this._linesIndices = new Array();
  96768. this._buffers = {};
  96769. this._checkVerticesInsteadOfIndices = false;
  96770. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  96771. this.isEnabled = true;
  96772. this._source = source;
  96773. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  96774. this._epsilon = epsilon;
  96775. this._prepareRessources();
  96776. this._generateEdgesLines();
  96777. }
  96778. EdgesRenderer.prototype._prepareRessources = function () {
  96779. if (this._lineShader) {
  96780. return;
  96781. }
  96782. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  96783. attributes: ["position", "normal"],
  96784. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  96785. });
  96786. this._lineShader.disableDepthWrite = true;
  96787. this._lineShader.backFaceCulling = false;
  96788. };
  96789. EdgesRenderer.prototype._rebuild = function () {
  96790. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96791. if (buffer) {
  96792. buffer._rebuild();
  96793. }
  96794. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96795. if (buffer) {
  96796. buffer._rebuild();
  96797. }
  96798. var scene = this._source.getScene();
  96799. var engine = scene.getEngine();
  96800. this._ib = engine.createIndexBuffer(this._linesIndices);
  96801. };
  96802. EdgesRenderer.prototype.dispose = function () {
  96803. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96804. if (buffer) {
  96805. buffer.dispose();
  96806. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  96807. }
  96808. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96809. if (buffer) {
  96810. buffer.dispose();
  96811. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  96812. }
  96813. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  96814. this._lineShader.dispose();
  96815. };
  96816. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  96817. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  96818. return 0;
  96819. }
  96820. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  96821. return 1;
  96822. }
  96823. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  96824. return 2;
  96825. }
  96826. return -1;
  96827. };
  96828. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  96829. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  96830. return 0;
  96831. }
  96832. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  96833. return 1;
  96834. }
  96835. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  96836. return 2;
  96837. }
  96838. return -1;
  96839. };
  96840. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  96841. var needToCreateLine;
  96842. if (edge === undefined) {
  96843. needToCreateLine = true;
  96844. }
  96845. else {
  96846. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  96847. needToCreateLine = dotProduct < this._epsilon;
  96848. }
  96849. if (needToCreateLine) {
  96850. var offset = this._linesPositions.length / 3;
  96851. var normal = p0.subtract(p1);
  96852. normal.normalize();
  96853. // Positions
  96854. this._linesPositions.push(p0.x);
  96855. this._linesPositions.push(p0.y);
  96856. this._linesPositions.push(p0.z);
  96857. this._linesPositions.push(p0.x);
  96858. this._linesPositions.push(p0.y);
  96859. this._linesPositions.push(p0.z);
  96860. this._linesPositions.push(p1.x);
  96861. this._linesPositions.push(p1.y);
  96862. this._linesPositions.push(p1.z);
  96863. this._linesPositions.push(p1.x);
  96864. this._linesPositions.push(p1.y);
  96865. this._linesPositions.push(p1.z);
  96866. // Normals
  96867. this._linesNormals.push(p1.x);
  96868. this._linesNormals.push(p1.y);
  96869. this._linesNormals.push(p1.z);
  96870. this._linesNormals.push(-1);
  96871. this._linesNormals.push(p1.x);
  96872. this._linesNormals.push(p1.y);
  96873. this._linesNormals.push(p1.z);
  96874. this._linesNormals.push(1);
  96875. this._linesNormals.push(p0.x);
  96876. this._linesNormals.push(p0.y);
  96877. this._linesNormals.push(p0.z);
  96878. this._linesNormals.push(-1);
  96879. this._linesNormals.push(p0.x);
  96880. this._linesNormals.push(p0.y);
  96881. this._linesNormals.push(p0.z);
  96882. this._linesNormals.push(1);
  96883. // Indices
  96884. this._linesIndices.push(offset);
  96885. this._linesIndices.push(offset + 1);
  96886. this._linesIndices.push(offset + 2);
  96887. this._linesIndices.push(offset);
  96888. this._linesIndices.push(offset + 2);
  96889. this._linesIndices.push(offset + 3);
  96890. }
  96891. };
  96892. EdgesRenderer.prototype._generateEdgesLines = function () {
  96893. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96894. var indices = this._source.getIndices();
  96895. if (!indices || !positions) {
  96896. return;
  96897. }
  96898. // First let's find adjacencies
  96899. var adjacencies = new Array();
  96900. var faceNormals = new Array();
  96901. var index;
  96902. var faceAdjacencies;
  96903. // Prepare faces
  96904. for (index = 0; index < indices.length; index += 3) {
  96905. faceAdjacencies = new FaceAdjacencies();
  96906. var p0Index = indices[index];
  96907. var p1Index = indices[index + 1];
  96908. var p2Index = indices[index + 2];
  96909. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  96910. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  96911. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  96912. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  96913. faceNormal.normalize();
  96914. faceNormals.push(faceNormal);
  96915. adjacencies.push(faceAdjacencies);
  96916. }
  96917. // Scan
  96918. for (index = 0; index < adjacencies.length; index++) {
  96919. faceAdjacencies = adjacencies[index];
  96920. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  96921. var otherFaceAdjacencies = adjacencies[otherIndex];
  96922. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  96923. break;
  96924. }
  96925. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  96926. continue;
  96927. }
  96928. var otherP0 = indices[otherIndex * 3];
  96929. var otherP1 = indices[otherIndex * 3 + 1];
  96930. var otherP2 = indices[otherIndex * 3 + 2];
  96931. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  96932. var otherEdgeIndex = 0;
  96933. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  96934. continue;
  96935. }
  96936. switch (edgeIndex) {
  96937. case 0:
  96938. if (this._checkVerticesInsteadOfIndices) {
  96939. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96940. }
  96941. else {
  96942. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  96943. }
  96944. break;
  96945. case 1:
  96946. if (this._checkVerticesInsteadOfIndices) {
  96947. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96948. }
  96949. else {
  96950. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  96951. }
  96952. break;
  96953. case 2:
  96954. if (this._checkVerticesInsteadOfIndices) {
  96955. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96956. }
  96957. else {
  96958. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  96959. }
  96960. break;
  96961. }
  96962. if (otherEdgeIndex === -1) {
  96963. continue;
  96964. }
  96965. faceAdjacencies.edges[edgeIndex] = otherIndex;
  96966. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  96967. faceAdjacencies.edgesConnectedCount++;
  96968. otherFaceAdjacencies.edgesConnectedCount++;
  96969. if (faceAdjacencies.edgesConnectedCount === 3) {
  96970. break;
  96971. }
  96972. }
  96973. }
  96974. }
  96975. // Create lines
  96976. for (index = 0; index < adjacencies.length; index++) {
  96977. // 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
  96978. var current = adjacencies[index];
  96979. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  96980. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  96981. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  96982. }
  96983. // Merge into a single mesh
  96984. var engine = this._source.getScene().getEngine();
  96985. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  96986. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  96987. this._ib = engine.createIndexBuffer(this._linesIndices);
  96988. this._indicesCount = this._linesIndices.length;
  96989. };
  96990. EdgesRenderer.prototype.render = function () {
  96991. var scene = this._source.getScene();
  96992. if (!this._lineShader.isReady() || !scene.activeCamera) {
  96993. return;
  96994. }
  96995. var engine = scene.getEngine();
  96996. this._lineShader._preBind();
  96997. // VBOs
  96998. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  96999. scene.resetCachedMaterial();
  97000. this._lineShader.setColor4("color", this._source.edgesColor);
  97001. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  97002. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  97003. }
  97004. else {
  97005. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  97006. }
  97007. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  97008. this._lineShader.bind(this._source.getWorldMatrix());
  97009. // Draw order
  97010. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  97011. this._lineShader.unbind();
  97012. engine.setDepthWrite(true);
  97013. };
  97014. return EdgesRenderer;
  97015. }());
  97016. BABYLON.EdgesRenderer = EdgesRenderer;
  97017. })(BABYLON || (BABYLON = {}));
  97018. //# sourceMappingURL=babylon.edgesRenderer.js.map
  97019. var BABYLON;
  97020. (function (BABYLON) {
  97021. // Adds the parser to the scene parsers.
  97022. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  97023. if (parsedData.effectLayers) {
  97024. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  97025. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  97026. container.effectLayers.push(effectLayer);
  97027. }
  97028. }
  97029. });
  97030. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  97031. var index = this.effectLayers.indexOf(toRemove);
  97032. if (index !== -1) {
  97033. this.effectLayers.splice(index, 1);
  97034. }
  97035. return index;
  97036. };
  97037. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  97038. this.effectLayers.push(newEffectLayer);
  97039. };
  97040. /**
  97041. * Defines the layer scene component responsible to manage any effect layers
  97042. * in a given scene.
  97043. */
  97044. var EffectLayerSceneComponent = /** @class */ (function () {
  97045. /**
  97046. * Creates a new instance of the component for the given scene
  97047. * @param scene Defines the scene to register the component in
  97048. */
  97049. function EffectLayerSceneComponent(scene) {
  97050. /**
  97051. * The component name helpfull to identify the component in the list of scene components.
  97052. */
  97053. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  97054. this._renderEffects = false;
  97055. this._needStencil = false;
  97056. this._previousStencilState = false;
  97057. this.scene = scene;
  97058. this._engine = scene.getEngine();
  97059. scene.effectLayers = new Array();
  97060. }
  97061. /**
  97062. * Registers the component in a given scene
  97063. */
  97064. EffectLayerSceneComponent.prototype.register = function () {
  97065. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  97066. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  97067. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  97068. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  97069. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  97070. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  97071. };
  97072. /**
  97073. * Rebuilds the elements related to this component in case of
  97074. * context lost for instance.
  97075. */
  97076. EffectLayerSceneComponent.prototype.rebuild = function () {
  97077. var layers = this.scene.effectLayers;
  97078. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  97079. var effectLayer = layers_1[_i];
  97080. effectLayer._rebuild();
  97081. }
  97082. };
  97083. /**
  97084. * Serializes the component data to the specified json object
  97085. * @param serializationObject The object to serialize to
  97086. */
  97087. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  97088. // Effect layers
  97089. serializationObject.effectLayers = [];
  97090. var layers = this.scene.effectLayers;
  97091. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  97092. var effectLayer = layers_2[_i];
  97093. if (effectLayer.serialize) {
  97094. serializationObject.effectLayers.push(effectLayer.serialize());
  97095. }
  97096. }
  97097. };
  97098. /**
  97099. * Adds all the element from the container to the scene
  97100. * @param container the container holding the elements
  97101. */
  97102. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  97103. var _this = this;
  97104. if (!container.effectLayers) {
  97105. return;
  97106. }
  97107. container.effectLayers.forEach(function (o) {
  97108. _this.scene.addEffectLayer(o);
  97109. });
  97110. };
  97111. /**
  97112. * Removes all the elements in the container from the scene
  97113. * @param container contains the elements to remove
  97114. */
  97115. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  97116. var _this = this;
  97117. if (!container.effectLayers) {
  97118. return;
  97119. }
  97120. container.effectLayers.forEach(function (o) {
  97121. _this.scene.removeEffectLayer(o);
  97122. });
  97123. };
  97124. /**
  97125. * Disposes the component and the associated ressources.
  97126. */
  97127. EffectLayerSceneComponent.prototype.dispose = function () {
  97128. var layers = this.scene.effectLayers;
  97129. while (layers.length) {
  97130. layers[0].dispose();
  97131. }
  97132. };
  97133. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  97134. var layers = this.scene.effectLayers;
  97135. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  97136. var layer = layers_3[_i];
  97137. if (!layer.hasMesh(mesh)) {
  97138. continue;
  97139. }
  97140. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  97141. var subMesh = _b[_a];
  97142. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  97143. return false;
  97144. }
  97145. }
  97146. }
  97147. return true;
  97148. };
  97149. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  97150. this._renderEffects = false;
  97151. this._needStencil = false;
  97152. var layers = this.scene.effectLayers;
  97153. if (layers && layers.length > 0) {
  97154. this._previousStencilState = this._engine.getStencilBuffer();
  97155. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  97156. var effectLayer = layers_4[_i];
  97157. if (effectLayer.shouldRender() &&
  97158. (!effectLayer.camera ||
  97159. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  97160. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  97161. this._renderEffects = true;
  97162. this._needStencil = this._needStencil || effectLayer.needStencil();
  97163. var renderTarget = effectLayer._mainTexture;
  97164. if (renderTarget._shouldRender()) {
  97165. this.scene.incrementRenderId();
  97166. renderTarget.render(false, false);
  97167. }
  97168. }
  97169. }
  97170. this.scene.incrementRenderId();
  97171. }
  97172. };
  97173. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  97174. // Activate effect Layer stencil
  97175. if (this._needStencil) {
  97176. this._engine.setStencilBuffer(true);
  97177. }
  97178. };
  97179. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  97180. // Restore effect Layer stencil
  97181. if (this._needStencil) {
  97182. this._engine.setStencilBuffer(this._previousStencilState);
  97183. }
  97184. };
  97185. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  97186. if (this._renderEffects) {
  97187. this._engine.setDepthBuffer(false);
  97188. var layers = this.scene.effectLayers;
  97189. for (var i = 0; i < layers.length; i++) {
  97190. var effectLayer = layers[i];
  97191. if (effectLayer.renderingGroupId === renderingGroupId) {
  97192. if (effectLayer.shouldRender()) {
  97193. effectLayer.render();
  97194. }
  97195. }
  97196. }
  97197. this._engine.setDepthBuffer(true);
  97198. }
  97199. };
  97200. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  97201. if (this._renderEffects) {
  97202. this._draw(-1);
  97203. }
  97204. };
  97205. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  97206. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  97207. this._draw(index);
  97208. }
  97209. };
  97210. return EffectLayerSceneComponent;
  97211. }());
  97212. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  97213. })(BABYLON || (BABYLON = {}));
  97214. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  97215. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97216. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97217. s = arguments[i];
  97218. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97219. t[p] = s[p];
  97220. }
  97221. return t;
  97222. };
  97223. var BABYLON;
  97224. (function (BABYLON) {
  97225. /**
  97226. * The effect layer Helps adding post process effect blended with the main pass.
  97227. *
  97228. * This can be for instance use to generate glow or higlight effects on the scene.
  97229. *
  97230. * The effect layer class can not be used directly and is intented to inherited from to be
  97231. * customized per effects.
  97232. */
  97233. var EffectLayer = /** @class */ (function () {
  97234. /**
  97235. * Instantiates a new effect Layer and references it in the scene.
  97236. * @param name The name of the layer
  97237. * @param scene The scene to use the layer in
  97238. */
  97239. function EffectLayer(
  97240. /** The Friendly of the effect in the scene */
  97241. name, scene) {
  97242. this._vertexBuffers = {};
  97243. this._maxSize = 0;
  97244. this._mainTextureDesiredSize = { width: 0, height: 0 };
  97245. this._shouldRender = true;
  97246. this._postProcesses = [];
  97247. this._textures = [];
  97248. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  97249. /**
  97250. * The clear color of the texture used to generate the glow map.
  97251. */
  97252. this.neutralColor = new BABYLON.Color4();
  97253. /**
  97254. * Specifies wether the highlight layer is enabled or not.
  97255. */
  97256. this.isEnabled = true;
  97257. /**
  97258. * An event triggered when the effect layer has been disposed.
  97259. */
  97260. this.onDisposeObservable = new BABYLON.Observable();
  97261. /**
  97262. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  97263. */
  97264. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  97265. /**
  97266. * An event triggered when the generated texture is being merged in the scene.
  97267. */
  97268. this.onBeforeComposeObservable = new BABYLON.Observable();
  97269. /**
  97270. * An event triggered when the generated texture has been merged in the scene.
  97271. */
  97272. this.onAfterComposeObservable = new BABYLON.Observable();
  97273. /**
  97274. * An event triggered when the efffect layer changes its size.
  97275. */
  97276. this.onSizeChangedObservable = new BABYLON.Observable();
  97277. this.name = name;
  97278. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97279. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  97280. if (!component) {
  97281. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  97282. this._scene._addComponent(component);
  97283. }
  97284. this._engine = this._scene.getEngine();
  97285. this._maxSize = this._engine.getCaps().maxTextureSize;
  97286. this._scene.effectLayers.push(this);
  97287. // Generate Buffers
  97288. this._generateIndexBuffer();
  97289. this._genrateVertexBuffer();
  97290. }
  97291. Object.defineProperty(EffectLayer.prototype, "camera", {
  97292. /**
  97293. * Gets the camera attached to the layer.
  97294. */
  97295. get: function () {
  97296. return this._effectLayerOptions.camera;
  97297. },
  97298. enumerable: true,
  97299. configurable: true
  97300. });
  97301. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  97302. /**
  97303. * Gets the rendering group id the layer should render in.
  97304. */
  97305. get: function () {
  97306. return this._effectLayerOptions.renderingGroupId;
  97307. },
  97308. enumerable: true,
  97309. configurable: true
  97310. });
  97311. /**
  97312. * Initializes the effect layer with the required options.
  97313. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  97314. */
  97315. EffectLayer.prototype._init = function (options) {
  97316. // Adapt options
  97317. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  97318. this._setMainTextureSize();
  97319. this._createMainTexture();
  97320. this._createTextureAndPostProcesses();
  97321. this._mergeEffect = this._createMergeEffect();
  97322. };
  97323. /**
  97324. * Generates the index buffer of the full screen quad blending to the main canvas.
  97325. */
  97326. EffectLayer.prototype._generateIndexBuffer = function () {
  97327. // Indices
  97328. var indices = [];
  97329. indices.push(0);
  97330. indices.push(1);
  97331. indices.push(2);
  97332. indices.push(0);
  97333. indices.push(2);
  97334. indices.push(3);
  97335. this._indexBuffer = this._engine.createIndexBuffer(indices);
  97336. };
  97337. /**
  97338. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  97339. */
  97340. EffectLayer.prototype._genrateVertexBuffer = function () {
  97341. // VBO
  97342. var vertices = [];
  97343. vertices.push(1, 1);
  97344. vertices.push(-1, 1);
  97345. vertices.push(-1, -1);
  97346. vertices.push(1, -1);
  97347. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  97348. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  97349. };
  97350. /**
  97351. * Sets the main texture desired size which is the closest power of two
  97352. * of the engine canvas size.
  97353. */
  97354. EffectLayer.prototype._setMainTextureSize = function () {
  97355. if (this._effectLayerOptions.mainTextureFixedSize) {
  97356. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  97357. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  97358. }
  97359. else {
  97360. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  97361. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  97362. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  97363. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  97364. }
  97365. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  97366. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  97367. };
  97368. /**
  97369. * Creates the main texture for the effect layer.
  97370. */
  97371. EffectLayer.prototype._createMainTexture = function () {
  97372. var _this = this;
  97373. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  97374. width: this._mainTextureDesiredSize.width,
  97375. height: this._mainTextureDesiredSize.height
  97376. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  97377. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  97378. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97379. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97380. this._mainTexture.anisotropicFilteringLevel = 1;
  97381. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97382. this._mainTexture.renderParticles = false;
  97383. this._mainTexture.renderList = null;
  97384. this._mainTexture.ignoreCameraViewport = true;
  97385. // Custom render function
  97386. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  97387. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  97388. var index;
  97389. var engine = _this._scene.getEngine();
  97390. if (depthOnlySubMeshes.length) {
  97391. engine.setColorWrite(false);
  97392. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  97393. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  97394. }
  97395. engine.setColorWrite(true);
  97396. }
  97397. for (index = 0; index < opaqueSubMeshes.length; index++) {
  97398. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  97399. }
  97400. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  97401. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  97402. }
  97403. for (index = 0; index < transparentSubMeshes.length; index++) {
  97404. _this._renderSubMesh(transparentSubMeshes.data[index]);
  97405. }
  97406. };
  97407. this._mainTexture.onClearObservable.add(function (engine) {
  97408. engine.clear(_this.neutralColor, true, true, true);
  97409. });
  97410. };
  97411. /**
  97412. * Checks for the readiness of the element composing the layer.
  97413. * @param subMesh the mesh to check for
  97414. * @param useInstances specify wether or not to use instances to render the mesh
  97415. * @param emissiveTexture the associated emissive texture used to generate the glow
  97416. * @return true if ready otherwise, false
  97417. */
  97418. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  97419. var material = subMesh.getMaterial();
  97420. if (!material) {
  97421. return false;
  97422. }
  97423. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  97424. return false;
  97425. }
  97426. var defines = [];
  97427. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97428. var mesh = subMesh.getMesh();
  97429. var uv1 = false;
  97430. var uv2 = false;
  97431. // Alpha test
  97432. if (material && material.needAlphaTesting()) {
  97433. var alphaTexture = material.getAlphaTestTexture();
  97434. if (alphaTexture) {
  97435. defines.push("#define ALPHATEST");
  97436. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97437. alphaTexture.coordinatesIndex === 1) {
  97438. defines.push("#define DIFFUSEUV2");
  97439. uv2 = true;
  97440. }
  97441. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97442. defines.push("#define DIFFUSEUV1");
  97443. uv1 = true;
  97444. }
  97445. }
  97446. }
  97447. // Emissive
  97448. if (emissiveTexture) {
  97449. defines.push("#define EMISSIVE");
  97450. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97451. emissiveTexture.coordinatesIndex === 1) {
  97452. defines.push("#define EMISSIVEUV2");
  97453. uv2 = true;
  97454. }
  97455. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97456. defines.push("#define EMISSIVEUV1");
  97457. uv1 = true;
  97458. }
  97459. }
  97460. if (uv1) {
  97461. attribs.push(BABYLON.VertexBuffer.UVKind);
  97462. defines.push("#define UV1");
  97463. }
  97464. if (uv2) {
  97465. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97466. defines.push("#define UV2");
  97467. }
  97468. // Bones
  97469. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  97470. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  97471. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  97472. if (mesh.numBoneInfluencers > 4) {
  97473. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  97474. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  97475. }
  97476. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  97477. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  97478. }
  97479. else {
  97480. defines.push("#define NUM_BONE_INFLUENCERS 0");
  97481. }
  97482. // Morph targets
  97483. var manager = mesh.morphTargetManager;
  97484. var morphInfluencers = 0;
  97485. if (manager) {
  97486. if (manager.numInfluencers > 0) {
  97487. defines.push("#define MORPHTARGETS");
  97488. morphInfluencers = manager.numInfluencers;
  97489. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  97490. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  97491. }
  97492. }
  97493. // Instances
  97494. if (useInstances) {
  97495. defines.push("#define INSTANCES");
  97496. attribs.push("world0");
  97497. attribs.push("world1");
  97498. attribs.push("world2");
  97499. attribs.push("world3");
  97500. }
  97501. // Get correct effect
  97502. var join = defines.join("\n");
  97503. if (this._cachedDefines !== join) {
  97504. this._cachedDefines = join;
  97505. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  97506. }
  97507. return this._effectLayerMapGenerationEffect.isReady();
  97508. };
  97509. /**
  97510. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  97511. */
  97512. EffectLayer.prototype.render = function () {
  97513. var currentEffect = this._mergeEffect;
  97514. // Check
  97515. if (!currentEffect.isReady())
  97516. return;
  97517. for (var i = 0; i < this._postProcesses.length; i++) {
  97518. if (!this._postProcesses[i].isReady()) {
  97519. return;
  97520. }
  97521. }
  97522. var engine = this._scene.getEngine();
  97523. this.onBeforeComposeObservable.notifyObservers(this);
  97524. // Render
  97525. engine.enableEffect(currentEffect);
  97526. engine.setState(false);
  97527. // VBOs
  97528. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  97529. // Cache
  97530. var previousAlphaMode = engine.getAlphaMode();
  97531. // Go Blend.
  97532. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  97533. // Blends the map on the main canvas.
  97534. this._internalRender(currentEffect);
  97535. // Restore Alpha
  97536. engine.setAlphaMode(previousAlphaMode);
  97537. this.onAfterComposeObservable.notifyObservers(this);
  97538. // Handle size changes.
  97539. var size = this._mainTexture.getSize();
  97540. this._setMainTextureSize();
  97541. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  97542. // Recreate RTT and post processes on size change.
  97543. this.onSizeChangedObservable.notifyObservers(this);
  97544. this._disposeTextureAndPostProcesses();
  97545. this._createMainTexture();
  97546. this._createTextureAndPostProcesses();
  97547. }
  97548. };
  97549. /**
  97550. * Determine if a given mesh will be used in the current effect.
  97551. * @param mesh mesh to test
  97552. * @returns true if the mesh will be used
  97553. */
  97554. EffectLayer.prototype.hasMesh = function (mesh) {
  97555. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  97556. return true;
  97557. }
  97558. return false;
  97559. };
  97560. /**
  97561. * Returns true if the layer contains information to display, otherwise false.
  97562. * @returns true if the glow layer should be rendered
  97563. */
  97564. EffectLayer.prototype.shouldRender = function () {
  97565. return this.isEnabled && this._shouldRender;
  97566. };
  97567. /**
  97568. * Returns true if the mesh should render, otherwise false.
  97569. * @param mesh The mesh to render
  97570. * @returns true if it should render otherwise false
  97571. */
  97572. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  97573. return true;
  97574. };
  97575. /**
  97576. * Returns true if the mesh should render, otherwise false.
  97577. * @param mesh The mesh to render
  97578. * @returns true if it should render otherwise false
  97579. */
  97580. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  97581. return true;
  97582. };
  97583. /**
  97584. * Renders the submesh passed in parameter to the generation map.
  97585. */
  97586. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  97587. var _this = this;
  97588. if (!this.shouldRender()) {
  97589. return;
  97590. }
  97591. var material = subMesh.getMaterial();
  97592. var mesh = subMesh.getRenderingMesh();
  97593. var scene = this._scene;
  97594. var engine = scene.getEngine();
  97595. if (!material) {
  97596. return;
  97597. }
  97598. // Do not block in blend mode.
  97599. if (material.needAlphaBlendingForMesh(mesh)) {
  97600. return;
  97601. }
  97602. // Culling
  97603. engine.setState(material.backFaceCulling);
  97604. // Managing instances
  97605. var batch = mesh._getInstancesRenderList(subMesh._id);
  97606. if (batch.mustReturn) {
  97607. return;
  97608. }
  97609. // Early Exit per mesh
  97610. if (!this._shouldRenderMesh(mesh)) {
  97611. return;
  97612. }
  97613. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  97614. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  97615. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  97616. engine.enableEffect(this._effectLayerMapGenerationEffect);
  97617. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  97618. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  97619. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  97620. // Alpha test
  97621. if (material && material.needAlphaTesting()) {
  97622. var alphaTexture = material.getAlphaTestTexture();
  97623. if (alphaTexture) {
  97624. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  97625. var textureMatrix = alphaTexture.getTextureMatrix();
  97626. if (textureMatrix) {
  97627. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  97628. }
  97629. }
  97630. }
  97631. // Glow emissive only
  97632. if (this._emissiveTextureAndColor.texture) {
  97633. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  97634. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  97635. }
  97636. // Bones
  97637. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  97638. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  97639. }
  97640. // Morph targets
  97641. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  97642. // Draw
  97643. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  97644. }
  97645. else {
  97646. // Need to reset refresh rate of the main map
  97647. this._mainTexture.resetRefreshCounter();
  97648. }
  97649. };
  97650. /**
  97651. * Rebuild the required buffers.
  97652. * @hidden Internal use only.
  97653. */
  97654. EffectLayer.prototype._rebuild = function () {
  97655. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97656. if (vb) {
  97657. vb._rebuild();
  97658. }
  97659. this._generateIndexBuffer();
  97660. };
  97661. /**
  97662. * Dispose only the render target textures and post process.
  97663. */
  97664. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  97665. this._mainTexture.dispose();
  97666. for (var i = 0; i < this._postProcesses.length; i++) {
  97667. if (this._postProcesses[i]) {
  97668. this._postProcesses[i].dispose();
  97669. }
  97670. }
  97671. this._postProcesses = [];
  97672. for (var i = 0; i < this._textures.length; i++) {
  97673. if (this._textures[i]) {
  97674. this._textures[i].dispose();
  97675. }
  97676. }
  97677. this._textures = [];
  97678. };
  97679. /**
  97680. * Dispose the highlight layer and free resources.
  97681. */
  97682. EffectLayer.prototype.dispose = function () {
  97683. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97684. if (vertexBuffer) {
  97685. vertexBuffer.dispose();
  97686. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97687. }
  97688. if (this._indexBuffer) {
  97689. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97690. this._indexBuffer = null;
  97691. }
  97692. // Clean textures and post processes
  97693. this._disposeTextureAndPostProcesses();
  97694. // Remove from scene
  97695. var index = this._scene.effectLayers.indexOf(this, 0);
  97696. if (index > -1) {
  97697. this._scene.effectLayers.splice(index, 1);
  97698. }
  97699. // Callback
  97700. this.onDisposeObservable.notifyObservers(this);
  97701. this.onDisposeObservable.clear();
  97702. this.onBeforeRenderMainTextureObservable.clear();
  97703. this.onBeforeComposeObservable.clear();
  97704. this.onAfterComposeObservable.clear();
  97705. this.onSizeChangedObservable.clear();
  97706. };
  97707. /**
  97708. * Gets the class name of the effect layer
  97709. * @returns the string with the class name of the effect layer
  97710. */
  97711. EffectLayer.prototype.getClassName = function () {
  97712. return "EffectLayer";
  97713. };
  97714. /**
  97715. * Creates an effect layer from parsed effect layer data
  97716. * @param parsedEffectLayer defines effect layer data
  97717. * @param scene defines the current scene
  97718. * @param rootUrl defines the root URL containing the effect layer information
  97719. * @returns a parsed effect Layer
  97720. */
  97721. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  97722. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  97723. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  97724. };
  97725. __decorate([
  97726. BABYLON.serialize()
  97727. ], EffectLayer.prototype, "name", void 0);
  97728. __decorate([
  97729. BABYLON.serializeAsColor4()
  97730. ], EffectLayer.prototype, "neutralColor", void 0);
  97731. __decorate([
  97732. BABYLON.serialize()
  97733. ], EffectLayer.prototype, "isEnabled", void 0);
  97734. __decorate([
  97735. BABYLON.serializeAsCameraReference()
  97736. ], EffectLayer.prototype, "camera", null);
  97737. __decorate([
  97738. BABYLON.serialize()
  97739. ], EffectLayer.prototype, "renderingGroupId", null);
  97740. return EffectLayer;
  97741. }());
  97742. BABYLON.EffectLayer = EffectLayer;
  97743. })(BABYLON || (BABYLON = {}));
  97744. //# sourceMappingURL=babylon.effectLayer.js.map
  97745. var BABYLON;
  97746. (function (BABYLON) {
  97747. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  97748. for (var index = 0; index < this.effectLayers.length; index++) {
  97749. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  97750. return this.effectLayers[index];
  97751. }
  97752. }
  97753. return null;
  97754. };
  97755. /**
  97756. * Special Glow Blur post process only blurring the alpha channel
  97757. * It enforces keeping the most luminous color in the color channel.
  97758. */
  97759. var GlowBlurPostProcess = /** @class */ (function (_super) {
  97760. __extends(GlowBlurPostProcess, _super);
  97761. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  97762. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  97763. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  97764. _this.direction = direction;
  97765. _this.kernel = kernel;
  97766. _this.onApplyObservable.add(function (effect) {
  97767. effect.setFloat2("screenSize", _this.width, _this.height);
  97768. effect.setVector2("direction", _this.direction);
  97769. effect.setFloat("blurWidth", _this.kernel);
  97770. });
  97771. return _this;
  97772. }
  97773. return GlowBlurPostProcess;
  97774. }(BABYLON.PostProcess));
  97775. /**
  97776. * The highlight layer Helps adding a glow effect around a mesh.
  97777. *
  97778. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97779. * glowy meshes to your scene.
  97780. *
  97781. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  97782. */
  97783. var HighlightLayer = /** @class */ (function (_super) {
  97784. __extends(HighlightLayer, _super);
  97785. /**
  97786. * Instantiates a new highlight Layer and references it to the scene..
  97787. * @param name The name of the layer
  97788. * @param scene The scene to use the layer in
  97789. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  97790. */
  97791. function HighlightLayer(name, scene, options) {
  97792. var _this = _super.call(this, name, scene) || this;
  97793. _this.name = name;
  97794. /**
  97795. * Specifies whether or not the inner glow is ACTIVE in the layer.
  97796. */
  97797. _this.innerGlow = true;
  97798. /**
  97799. * Specifies whether or not the outer glow is ACTIVE in the layer.
  97800. */
  97801. _this.outerGlow = true;
  97802. /**
  97803. * An event triggered when the highlight layer is being blurred.
  97804. */
  97805. _this.onBeforeBlurObservable = new BABYLON.Observable();
  97806. /**
  97807. * An event triggered when the highlight layer has been blurred.
  97808. */
  97809. _this.onAfterBlurObservable = new BABYLON.Observable();
  97810. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  97811. _this._meshes = {};
  97812. _this._excludedMeshes = {};
  97813. _this.neutralColor = HighlightLayer.NeutralColor;
  97814. // Warn on stencil
  97815. if (!_this._engine.isStencilEnable) {
  97816. 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 }");
  97817. }
  97818. // Adapt options
  97819. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  97820. // Initialize the layer
  97821. _this._init({
  97822. alphaBlendingMode: _this._options.alphaBlendingMode,
  97823. camera: _this._options.camera,
  97824. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97825. mainTextureRatio: _this._options.mainTextureRatio,
  97826. renderingGroupId: _this._options.renderingGroupId
  97827. });
  97828. // Do not render as long as no meshes have been added
  97829. _this._shouldRender = false;
  97830. return _this;
  97831. }
  97832. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  97833. /**
  97834. * Gets the horizontal size of the blur.
  97835. */
  97836. get: function () {
  97837. return this._horizontalBlurPostprocess.kernel;
  97838. },
  97839. /**
  97840. * Specifies the horizontal size of the blur.
  97841. */
  97842. set: function (value) {
  97843. this._horizontalBlurPostprocess.kernel = value;
  97844. },
  97845. enumerable: true,
  97846. configurable: true
  97847. });
  97848. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  97849. /**
  97850. * Gets the vertical size of the blur.
  97851. */
  97852. get: function () {
  97853. return this._verticalBlurPostprocess.kernel;
  97854. },
  97855. /**
  97856. * Specifies the vertical size of the blur.
  97857. */
  97858. set: function (value) {
  97859. this._verticalBlurPostprocess.kernel = value;
  97860. },
  97861. enumerable: true,
  97862. configurable: true
  97863. });
  97864. /**
  97865. * Get the effect name of the layer.
  97866. * @return The effect name
  97867. */
  97868. HighlightLayer.prototype.getEffectName = function () {
  97869. return HighlightLayer.EffectName;
  97870. };
  97871. /**
  97872. * Create the merge effect. This is the shader use to blit the information back
  97873. * to the main canvas at the end of the scene rendering.
  97874. */
  97875. HighlightLayer.prototype._createMergeEffect = function () {
  97876. // Effect
  97877. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  97878. };
  97879. /**
  97880. * Creates the render target textures and post processes used in the highlight layer.
  97881. */
  97882. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  97883. var _this = this;
  97884. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  97885. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  97886. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97887. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97888. var textureType = 0;
  97889. if (this._engine.getCaps().textureHalfFloatRender) {
  97890. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97891. }
  97892. else {
  97893. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97894. }
  97895. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  97896. width: blurTextureWidth,
  97897. height: blurTextureHeight
  97898. }, this._scene, false, true, textureType);
  97899. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97900. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97901. this._blurTexture.anisotropicFilteringLevel = 16;
  97902. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  97903. this._blurTexture.renderParticles = false;
  97904. this._blurTexture.ignoreCameraViewport = true;
  97905. this._textures = [this._blurTexture];
  97906. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  97907. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97908. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  97909. effect.setTexture("textureSampler", _this._mainTexture);
  97910. });
  97911. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97912. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97913. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97914. });
  97915. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97916. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  97917. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97918. });
  97919. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97920. }
  97921. else {
  97922. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  97923. width: blurTextureWidth,
  97924. height: blurTextureHeight
  97925. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97926. this._horizontalBlurPostprocess.width = blurTextureWidth;
  97927. this._horizontalBlurPostprocess.height = blurTextureHeight;
  97928. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97929. effect.setTexture("textureSampler", _this._mainTexture);
  97930. });
  97931. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  97932. width: blurTextureWidth,
  97933. height: blurTextureHeight
  97934. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97935. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97936. }
  97937. this._mainTexture.onAfterUnbindObservable.add(function () {
  97938. _this.onBeforeBlurObservable.notifyObservers(_this);
  97939. var internalTexture = _this._blurTexture.getInternalTexture();
  97940. if (internalTexture) {
  97941. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  97942. }
  97943. _this.onAfterBlurObservable.notifyObservers(_this);
  97944. });
  97945. // Prevent autoClear.
  97946. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97947. };
  97948. /**
  97949. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97950. */
  97951. HighlightLayer.prototype.needStencil = function () {
  97952. return true;
  97953. };
  97954. /**
  97955. * Checks for the readiness of the element composing the layer.
  97956. * @param subMesh the mesh to check for
  97957. * @param useInstances specify wether or not to use instances to render the mesh
  97958. * @param emissiveTexture the associated emissive texture used to generate the glow
  97959. * @return true if ready otherwise, false
  97960. */
  97961. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  97962. var material = subMesh.getMaterial();
  97963. var mesh = subMesh.getRenderingMesh();
  97964. if (!material || !mesh || !this._meshes) {
  97965. return false;
  97966. }
  97967. var emissiveTexture = null;
  97968. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97969. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97970. emissiveTexture = material.emissiveTexture;
  97971. }
  97972. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97973. };
  97974. /**
  97975. * Implementation specific of rendering the generating effect on the main canvas.
  97976. * @param effect The effect used to render through
  97977. */
  97978. HighlightLayer.prototype._internalRender = function (effect) {
  97979. // Texture
  97980. effect.setTexture("textureSampler", this._blurTexture);
  97981. // Cache
  97982. var engine = this._engine;
  97983. var previousStencilBuffer = engine.getStencilBuffer();
  97984. var previousStencilFunction = engine.getStencilFunction();
  97985. var previousStencilMask = engine.getStencilMask();
  97986. var previousStencilOperationPass = engine.getStencilOperationPass();
  97987. var previousStencilOperationFail = engine.getStencilOperationFail();
  97988. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  97989. var previousStencilReference = engine.getStencilFunctionReference();
  97990. // Stencil operations
  97991. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  97992. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  97993. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  97994. // Draw order
  97995. engine.setStencilMask(0x00);
  97996. engine.setStencilBuffer(true);
  97997. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  97998. // 2 passes inner outer
  97999. if (this.outerGlow) {
  98000. effect.setFloat("offset", 0);
  98001. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  98002. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98003. }
  98004. if (this.innerGlow) {
  98005. effect.setFloat("offset", 1);
  98006. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  98007. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98008. }
  98009. // Restore Cache
  98010. engine.setStencilFunction(previousStencilFunction);
  98011. engine.setStencilMask(previousStencilMask);
  98012. engine.setStencilBuffer(previousStencilBuffer);
  98013. engine.setStencilOperationPass(previousStencilOperationPass);
  98014. engine.setStencilOperationFail(previousStencilOperationFail);
  98015. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  98016. engine.setStencilFunctionReference(previousStencilReference);
  98017. };
  98018. /**
  98019. * Returns true if the layer contains information to display, otherwise false.
  98020. */
  98021. HighlightLayer.prototype.shouldRender = function () {
  98022. if (_super.prototype.shouldRender.call(this)) {
  98023. return this._meshes ? true : false;
  98024. }
  98025. return false;
  98026. };
  98027. /**
  98028. * Returns true if the mesh should render, otherwise false.
  98029. * @param mesh The mesh to render
  98030. * @returns true if it should render otherwise false
  98031. */
  98032. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  98033. // Excluded Mesh
  98034. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  98035. return false;
  98036. }
  98037. ;
  98038. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98039. return false;
  98040. }
  98041. return true;
  98042. };
  98043. /**
  98044. * Sets the required values for both the emissive texture and and the main color.
  98045. */
  98046. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98047. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  98048. if (highlightLayerMesh) {
  98049. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  98050. }
  98051. else {
  98052. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98053. }
  98054. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  98055. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98056. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  98057. }
  98058. else {
  98059. this._emissiveTextureAndColor.texture = null;
  98060. }
  98061. };
  98062. /**
  98063. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  98064. * @param mesh The mesh to exclude from the highlight layer
  98065. */
  98066. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  98067. if (!this._excludedMeshes) {
  98068. return;
  98069. }
  98070. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98071. if (!meshExcluded) {
  98072. this._excludedMeshes[mesh.uniqueId] = {
  98073. mesh: mesh,
  98074. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  98075. mesh.getEngine().setStencilBuffer(false);
  98076. }),
  98077. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  98078. mesh.getEngine().setStencilBuffer(true);
  98079. }),
  98080. };
  98081. }
  98082. };
  98083. /**
  98084. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  98085. * @param mesh The mesh to highlight
  98086. */
  98087. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  98088. if (!this._excludedMeshes) {
  98089. return;
  98090. }
  98091. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98092. if (meshExcluded) {
  98093. if (meshExcluded.beforeRender) {
  98094. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  98095. }
  98096. if (meshExcluded.afterRender) {
  98097. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  98098. }
  98099. }
  98100. this._excludedMeshes[mesh.uniqueId] = null;
  98101. };
  98102. /**
  98103. * Determine if a given mesh will be highlighted by the current HighlightLayer
  98104. * @param mesh mesh to test
  98105. * @returns true if the mesh will be highlighted by the current HighlightLayer
  98106. */
  98107. HighlightLayer.prototype.hasMesh = function (mesh) {
  98108. if (!this._meshes) {
  98109. return false;
  98110. }
  98111. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98112. return false;
  98113. }
  98114. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  98115. };
  98116. /**
  98117. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  98118. * @param mesh The mesh to highlight
  98119. * @param color The color of the highlight
  98120. * @param glowEmissiveOnly Extract the glow from the emissive texture
  98121. */
  98122. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  98123. var _this = this;
  98124. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  98125. if (!this._meshes) {
  98126. return;
  98127. }
  98128. var meshHighlight = this._meshes[mesh.uniqueId];
  98129. if (meshHighlight) {
  98130. meshHighlight.color = color;
  98131. }
  98132. else {
  98133. this._meshes[mesh.uniqueId] = {
  98134. mesh: mesh,
  98135. color: color,
  98136. // Lambda required for capture due to Observable this context
  98137. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  98138. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  98139. _this._defaultStencilReference(mesh);
  98140. }
  98141. else {
  98142. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  98143. }
  98144. }),
  98145. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  98146. glowEmissiveOnly: glowEmissiveOnly
  98147. };
  98148. mesh.onDisposeObservable.add(function () {
  98149. _this._disposeMesh(mesh);
  98150. });
  98151. }
  98152. this._shouldRender = true;
  98153. };
  98154. /**
  98155. * Remove a mesh from the highlight layer in order to make it stop glowing.
  98156. * @param mesh The mesh to highlight
  98157. */
  98158. HighlightLayer.prototype.removeMesh = function (mesh) {
  98159. if (!this._meshes) {
  98160. return;
  98161. }
  98162. var meshHighlight = this._meshes[mesh.uniqueId];
  98163. if (meshHighlight) {
  98164. if (meshHighlight.observerHighlight) {
  98165. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98166. }
  98167. if (meshHighlight.observerDefault) {
  98168. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98169. }
  98170. delete this._meshes[mesh.uniqueId];
  98171. }
  98172. this._shouldRender = false;
  98173. for (var meshHighlightToCheck in this._meshes) {
  98174. if (this._meshes[meshHighlightToCheck]) {
  98175. this._shouldRender = true;
  98176. break;
  98177. }
  98178. }
  98179. };
  98180. /**
  98181. * Force the stencil to the normal expected value for none glowing parts
  98182. */
  98183. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  98184. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  98185. };
  98186. /**
  98187. * Free any resources and references associated to a mesh.
  98188. * Internal use
  98189. * @param mesh The mesh to free.
  98190. */
  98191. HighlightLayer.prototype._disposeMesh = function (mesh) {
  98192. this.removeMesh(mesh);
  98193. this.removeExcludedMesh(mesh);
  98194. };
  98195. /**
  98196. * Dispose the highlight layer and free resources.
  98197. */
  98198. HighlightLayer.prototype.dispose = function () {
  98199. if (this._meshes) {
  98200. // Clean mesh references
  98201. for (var id in this._meshes) {
  98202. var meshHighlight = this._meshes[id];
  98203. if (meshHighlight && meshHighlight.mesh) {
  98204. if (meshHighlight.observerHighlight) {
  98205. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98206. }
  98207. if (meshHighlight.observerDefault) {
  98208. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98209. }
  98210. }
  98211. }
  98212. this._meshes = null;
  98213. }
  98214. if (this._excludedMeshes) {
  98215. for (var id in this._excludedMeshes) {
  98216. var meshHighlight = this._excludedMeshes[id];
  98217. if (meshHighlight) {
  98218. if (meshHighlight.beforeRender) {
  98219. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  98220. }
  98221. if (meshHighlight.afterRender) {
  98222. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  98223. }
  98224. }
  98225. }
  98226. this._excludedMeshes = null;
  98227. }
  98228. _super.prototype.dispose.call(this);
  98229. };
  98230. /**
  98231. * Gets the class name of the effect layer
  98232. * @returns the string with the class name of the effect layer
  98233. */
  98234. HighlightLayer.prototype.getClassName = function () {
  98235. return "HighlightLayer";
  98236. };
  98237. /**
  98238. * Serializes this Highlight layer
  98239. * @returns a serialized Highlight layer object
  98240. */
  98241. HighlightLayer.prototype.serialize = function () {
  98242. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98243. serializationObject.customType = "BABYLON.HighlightLayer";
  98244. // Highlighted meshes
  98245. serializationObject.meshes = [];
  98246. if (this._meshes) {
  98247. for (var m in this._meshes) {
  98248. var mesh = this._meshes[m];
  98249. if (mesh) {
  98250. serializationObject.meshes.push({
  98251. glowEmissiveOnly: mesh.glowEmissiveOnly,
  98252. color: mesh.color.asArray(),
  98253. meshId: mesh.mesh.id
  98254. });
  98255. }
  98256. }
  98257. }
  98258. // Excluded meshes
  98259. serializationObject.excludedMeshes = [];
  98260. if (this._excludedMeshes) {
  98261. for (var e in this._excludedMeshes) {
  98262. var excludedMesh = this._excludedMeshes[e];
  98263. if (excludedMesh) {
  98264. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  98265. }
  98266. }
  98267. }
  98268. return serializationObject;
  98269. };
  98270. /**
  98271. * Creates a Highlight layer from parsed Highlight layer data
  98272. * @param parsedHightlightLayer defines the Highlight layer data
  98273. * @param scene defines the current scene
  98274. * @param rootUrl defines the root URL containing the Highlight layer information
  98275. * @returns a parsed Highlight layer
  98276. */
  98277. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  98278. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  98279. var index;
  98280. // Excluded meshes
  98281. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  98282. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  98283. if (mesh) {
  98284. hl.addExcludedMesh(mesh);
  98285. }
  98286. }
  98287. // Included meshes
  98288. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  98289. var highlightedMesh = parsedHightlightLayer.meshes[index];
  98290. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  98291. if (mesh) {
  98292. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  98293. }
  98294. }
  98295. return hl;
  98296. };
  98297. /**
  98298. * Effect Name of the highlight layer.
  98299. */
  98300. HighlightLayer.EffectName = "HighlightLayer";
  98301. /**
  98302. * The neutral color used during the preparation of the glow effect.
  98303. * This is black by default as the blend operation is a blend operation.
  98304. */
  98305. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  98306. /**
  98307. * Stencil value used for glowing meshes.
  98308. */
  98309. HighlightLayer.GlowingMeshStencilReference = 0x02;
  98310. /**
  98311. * Stencil value used for the other meshes in the scene.
  98312. */
  98313. HighlightLayer.NormalMeshStencilReference = 0x01;
  98314. __decorate([
  98315. BABYLON.serialize()
  98316. ], HighlightLayer.prototype, "innerGlow", void 0);
  98317. __decorate([
  98318. BABYLON.serialize()
  98319. ], HighlightLayer.prototype, "outerGlow", void 0);
  98320. __decorate([
  98321. BABYLON.serialize()
  98322. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  98323. __decorate([
  98324. BABYLON.serialize()
  98325. ], HighlightLayer.prototype, "blurVerticalSize", null);
  98326. __decorate([
  98327. BABYLON.serialize("options")
  98328. ], HighlightLayer.prototype, "_options", void 0);
  98329. return HighlightLayer;
  98330. }(BABYLON.EffectLayer));
  98331. BABYLON.HighlightLayer = HighlightLayer;
  98332. })(BABYLON || (BABYLON = {}));
  98333. //# sourceMappingURL=babylon.highlightLayer.js.map
  98334. var BABYLON;
  98335. (function (BABYLON) {
  98336. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  98337. for (var index = 0; index < this.effectLayers.length; index++) {
  98338. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  98339. return this.effectLayers[index];
  98340. }
  98341. }
  98342. return null;
  98343. };
  98344. /**
  98345. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  98346. *
  98347. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  98348. * glowy meshes to your scene.
  98349. *
  98350. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  98351. */
  98352. var GlowLayer = /** @class */ (function (_super) {
  98353. __extends(GlowLayer, _super);
  98354. /**
  98355. * Instantiates a new glow Layer and references it to the scene.
  98356. * @param name The name of the layer
  98357. * @param scene The scene to use the layer in
  98358. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  98359. */
  98360. function GlowLayer(name, scene, options) {
  98361. var _this = _super.call(this, name, scene) || this;
  98362. _this._intensity = 1.0;
  98363. _this._includedOnlyMeshes = [];
  98364. _this._excludedMeshes = [];
  98365. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  98366. // Adapt options
  98367. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  98368. // Initialize the layer
  98369. _this._init({
  98370. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  98371. camera: _this._options.camera,
  98372. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  98373. mainTextureRatio: _this._options.mainTextureRatio,
  98374. renderingGroupId: _this._options.renderingGroupId
  98375. });
  98376. return _this;
  98377. }
  98378. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  98379. /**
  98380. * Gets the kernel size of the blur.
  98381. */
  98382. get: function () {
  98383. return this._horizontalBlurPostprocess1.kernel;
  98384. },
  98385. /**
  98386. * Sets the kernel size of the blur.
  98387. */
  98388. set: function (value) {
  98389. this._horizontalBlurPostprocess1.kernel = value;
  98390. this._verticalBlurPostprocess1.kernel = value;
  98391. this._horizontalBlurPostprocess2.kernel = value;
  98392. this._verticalBlurPostprocess2.kernel = value;
  98393. },
  98394. enumerable: true,
  98395. configurable: true
  98396. });
  98397. Object.defineProperty(GlowLayer.prototype, "intensity", {
  98398. /**
  98399. * Gets the glow intensity.
  98400. */
  98401. get: function () {
  98402. return this._intensity;
  98403. },
  98404. /**
  98405. * Sets the glow intensity.
  98406. */
  98407. set: function (value) {
  98408. this._intensity = value;
  98409. },
  98410. enumerable: true,
  98411. configurable: true
  98412. });
  98413. /**
  98414. * Get the effect name of the layer.
  98415. * @return The effect name
  98416. */
  98417. GlowLayer.prototype.getEffectName = function () {
  98418. return GlowLayer.EffectName;
  98419. };
  98420. /**
  98421. * Create the merge effect. This is the shader use to blit the information back
  98422. * to the main canvas at the end of the scene rendering.
  98423. */
  98424. GlowLayer.prototype._createMergeEffect = function () {
  98425. // Effect
  98426. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  98427. };
  98428. /**
  98429. * Creates the render target textures and post processes used in the glow layer.
  98430. */
  98431. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  98432. var _this = this;
  98433. var blurTextureWidth = this._mainTextureDesiredSize.width;
  98434. var blurTextureHeight = this._mainTextureDesiredSize.height;
  98435. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  98436. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  98437. var textureType = 0;
  98438. if (this._engine.getCaps().textureHalfFloatRender) {
  98439. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98440. }
  98441. else {
  98442. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98443. }
  98444. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  98445. width: blurTextureWidth,
  98446. height: blurTextureHeight
  98447. }, this._scene, false, true, textureType);
  98448. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98449. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98450. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98451. this._blurTexture1.renderParticles = false;
  98452. this._blurTexture1.ignoreCameraViewport = true;
  98453. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  98454. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  98455. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  98456. width: blurTextureWidth2,
  98457. height: blurTextureHeight2
  98458. }, this._scene, false, true, textureType);
  98459. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98460. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98461. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98462. this._blurTexture2.renderParticles = false;
  98463. this._blurTexture2.ignoreCameraViewport = true;
  98464. this._textures = [this._blurTexture1, this._blurTexture2];
  98465. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  98466. width: blurTextureWidth,
  98467. height: blurTextureHeight
  98468. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98469. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  98470. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  98471. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  98472. effect.setTexture("textureSampler", _this._mainTexture);
  98473. });
  98474. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  98475. width: blurTextureWidth,
  98476. height: blurTextureHeight
  98477. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98478. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  98479. width: blurTextureWidth2,
  98480. height: blurTextureHeight2
  98481. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98482. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  98483. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  98484. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  98485. effect.setTexture("textureSampler", _this._blurTexture1);
  98486. });
  98487. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  98488. width: blurTextureWidth2,
  98489. height: blurTextureHeight2
  98490. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98491. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98492. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  98493. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98494. this._mainTexture.samples = this._options.mainTextureSamples;
  98495. this._mainTexture.onAfterUnbindObservable.add(function () {
  98496. var internalTexture = _this._blurTexture1.getInternalTexture();
  98497. if (internalTexture) {
  98498. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  98499. internalTexture = _this._blurTexture2.getInternalTexture();
  98500. if (internalTexture) {
  98501. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  98502. }
  98503. }
  98504. });
  98505. // Prevent autoClear.
  98506. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  98507. };
  98508. /**
  98509. * Checks for the readiness of the element composing the layer.
  98510. * @param subMesh the mesh to check for
  98511. * @param useInstances specify wether or not to use instances to render the mesh
  98512. * @param emissiveTexture the associated emissive texture used to generate the glow
  98513. * @return true if ready otherwise, false
  98514. */
  98515. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  98516. var material = subMesh.getMaterial();
  98517. var mesh = subMesh.getRenderingMesh();
  98518. if (!material || !mesh) {
  98519. return false;
  98520. }
  98521. var emissiveTexture = material.emissiveTexture;
  98522. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  98523. };
  98524. /**
  98525. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  98526. */
  98527. GlowLayer.prototype.needStencil = function () {
  98528. return false;
  98529. };
  98530. /**
  98531. * Implementation specific of rendering the generating effect on the main canvas.
  98532. * @param effect The effect used to render through
  98533. */
  98534. GlowLayer.prototype._internalRender = function (effect) {
  98535. // Texture
  98536. effect.setTexture("textureSampler", this._blurTexture1);
  98537. effect.setTexture("textureSampler2", this._blurTexture2);
  98538. effect.setFloat("offset", this._intensity);
  98539. // Cache
  98540. var engine = this._engine;
  98541. var previousStencilBuffer = engine.getStencilBuffer();
  98542. // Draw order
  98543. engine.setStencilBuffer(false);
  98544. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98545. // Draw order
  98546. engine.setStencilBuffer(previousStencilBuffer);
  98547. };
  98548. /**
  98549. * Sets the required values for both the emissive texture and and the main color.
  98550. */
  98551. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98552. var textureLevel = 1.0;
  98553. if (this.customEmissiveTextureSelector) {
  98554. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  98555. }
  98556. else {
  98557. if (material) {
  98558. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98559. if (this._emissiveTextureAndColor.texture) {
  98560. textureLevel = this._emissiveTextureAndColor.texture.level;
  98561. }
  98562. }
  98563. else {
  98564. this._emissiveTextureAndColor.texture = null;
  98565. }
  98566. }
  98567. if (this.customEmissiveColorSelector) {
  98568. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  98569. }
  98570. else {
  98571. if (material.emissiveColor) {
  98572. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  98573. }
  98574. else {
  98575. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98576. }
  98577. }
  98578. };
  98579. /**
  98580. * Returns true if the mesh should render, otherwise false.
  98581. * @param mesh The mesh to render
  98582. * @returns true if it should render otherwise false
  98583. */
  98584. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  98585. return this.hasMesh(mesh);
  98586. };
  98587. /**
  98588. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  98589. * @param mesh The mesh to exclude from the glow layer
  98590. */
  98591. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  98592. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  98593. this._excludedMeshes.push(mesh.uniqueId);
  98594. }
  98595. };
  98596. /**
  98597. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  98598. * @param mesh The mesh to remove
  98599. */
  98600. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  98601. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  98602. if (index !== -1) {
  98603. this._excludedMeshes.splice(index, 1);
  98604. }
  98605. };
  98606. /**
  98607. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  98608. * @param mesh The mesh to include in the glow layer
  98609. */
  98610. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  98611. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  98612. this._includedOnlyMeshes.push(mesh.uniqueId);
  98613. }
  98614. };
  98615. /**
  98616. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  98617. * @param mesh The mesh to remove
  98618. */
  98619. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  98620. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  98621. if (index !== -1) {
  98622. this._includedOnlyMeshes.splice(index, 1);
  98623. }
  98624. };
  98625. /**
  98626. * Determine if a given mesh will be used in the glow layer
  98627. * @param mesh The mesh to test
  98628. * @returns true if the mesh will be highlighted by the current glow layer
  98629. */
  98630. GlowLayer.prototype.hasMesh = function (mesh) {
  98631. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98632. return false;
  98633. }
  98634. // Included Mesh
  98635. if (this._includedOnlyMeshes.length) {
  98636. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  98637. }
  98638. ;
  98639. // Excluded Mesh
  98640. if (this._excludedMeshes.length) {
  98641. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  98642. }
  98643. ;
  98644. return true;
  98645. };
  98646. /**
  98647. * Free any resources and references associated to a mesh.
  98648. * Internal use
  98649. * @param mesh The mesh to free.
  98650. */
  98651. GlowLayer.prototype._disposeMesh = function (mesh) {
  98652. this.removeIncludedOnlyMesh(mesh);
  98653. this.removeExcludedMesh(mesh);
  98654. };
  98655. /**
  98656. * Gets the class name of the effect layer
  98657. * @returns the string with the class name of the effect layer
  98658. */
  98659. GlowLayer.prototype.getClassName = function () {
  98660. return "GlowLayer";
  98661. };
  98662. /**
  98663. * Serializes this glow layer
  98664. * @returns a serialized glow layer object
  98665. */
  98666. GlowLayer.prototype.serialize = function () {
  98667. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98668. serializationObject.customType = "BABYLON.GlowLayer";
  98669. var index;
  98670. // Included meshes
  98671. serializationObject.includedMeshes = [];
  98672. if (this._includedOnlyMeshes.length) {
  98673. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  98674. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  98675. if (mesh) {
  98676. serializationObject.includedMeshes.push(mesh.id);
  98677. }
  98678. }
  98679. }
  98680. // Excluded meshes
  98681. serializationObject.excludedMeshes = [];
  98682. if (this._excludedMeshes.length) {
  98683. for (index = 0; index < this._excludedMeshes.length; index++) {
  98684. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  98685. if (mesh) {
  98686. serializationObject.excludedMeshes.push(mesh.id);
  98687. }
  98688. }
  98689. }
  98690. return serializationObject;
  98691. };
  98692. /**
  98693. * Creates a Glow Layer from parsed glow layer data
  98694. * @param parsedGlowLayer defines glow layer data
  98695. * @param scene defines the current scene
  98696. * @param rootUrl defines the root URL containing the glow layer information
  98697. * @returns a parsed Glow Layer
  98698. */
  98699. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  98700. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  98701. var index;
  98702. // Excluded meshes
  98703. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  98704. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  98705. if (mesh) {
  98706. gl.addExcludedMesh(mesh);
  98707. }
  98708. }
  98709. // Included meshes
  98710. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  98711. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  98712. if (mesh) {
  98713. gl.addIncludedOnlyMesh(mesh);
  98714. }
  98715. }
  98716. return gl;
  98717. };
  98718. /**
  98719. * Effect Name of the layer.
  98720. */
  98721. GlowLayer.EffectName = "GlowLayer";
  98722. /**
  98723. * The default blur kernel size used for the glow.
  98724. */
  98725. GlowLayer.DefaultBlurKernelSize = 32;
  98726. /**
  98727. * The default texture size ratio used for the glow.
  98728. */
  98729. GlowLayer.DefaultTextureRatio = 0.5;
  98730. __decorate([
  98731. BABYLON.serialize()
  98732. ], GlowLayer.prototype, "blurKernelSize", null);
  98733. __decorate([
  98734. BABYLON.serialize()
  98735. ], GlowLayer.prototype, "intensity", null);
  98736. __decorate([
  98737. BABYLON.serialize("options")
  98738. ], GlowLayer.prototype, "_options", void 0);
  98739. return GlowLayer;
  98740. }(BABYLON.EffectLayer));
  98741. BABYLON.GlowLayer = GlowLayer;
  98742. })(BABYLON || (BABYLON = {}));
  98743. //# sourceMappingURL=babylon.glowLayer.js.map
  98744. var BABYLON;
  98745. (function (BABYLON) {
  98746. /**
  98747. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  98748. */
  98749. var AssetTaskState;
  98750. (function (AssetTaskState) {
  98751. /**
  98752. * Initialization
  98753. */
  98754. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  98755. /**
  98756. * Running
  98757. */
  98758. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  98759. /**
  98760. * Done
  98761. */
  98762. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  98763. /**
  98764. * Error
  98765. */
  98766. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  98767. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  98768. /**
  98769. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  98770. */
  98771. var AbstractAssetTask = /** @class */ (function () {
  98772. /**
  98773. * Creates a new {BABYLON.AssetsManager}
  98774. * @param name defines the name of the task
  98775. */
  98776. function AbstractAssetTask(
  98777. /**
  98778. * Task name
  98779. */ name) {
  98780. this.name = name;
  98781. this._isCompleted = false;
  98782. this._taskState = AssetTaskState.INIT;
  98783. }
  98784. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  98785. /**
  98786. * Get if the task is completed
  98787. */
  98788. get: function () {
  98789. return this._isCompleted;
  98790. },
  98791. enumerable: true,
  98792. configurable: true
  98793. });
  98794. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  98795. /**
  98796. * Gets the current state of the task
  98797. */
  98798. get: function () {
  98799. return this._taskState;
  98800. },
  98801. enumerable: true,
  98802. configurable: true
  98803. });
  98804. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  98805. /**
  98806. * Gets the current error object (if task is in error)
  98807. */
  98808. get: function () {
  98809. return this._errorObject;
  98810. },
  98811. enumerable: true,
  98812. configurable: true
  98813. });
  98814. /**
  98815. * Internal only
  98816. * @hidden
  98817. */
  98818. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  98819. if (this._errorObject) {
  98820. return;
  98821. }
  98822. this._errorObject = {
  98823. message: message,
  98824. exception: exception
  98825. };
  98826. };
  98827. /**
  98828. * Execute the current task
  98829. * @param scene defines the scene where you want your assets to be loaded
  98830. * @param onSuccess is a callback called when the task is successfully executed
  98831. * @param onError is a callback called if an error occurs
  98832. */
  98833. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98834. var _this = this;
  98835. this._taskState = AssetTaskState.RUNNING;
  98836. this.runTask(scene, function () {
  98837. _this.onDoneCallback(onSuccess, onError);
  98838. }, function (msg, exception) {
  98839. _this.onErrorCallback(onError, msg, exception);
  98840. });
  98841. };
  98842. /**
  98843. * Execute the current task
  98844. * @param scene defines the scene where you want your assets to be loaded
  98845. * @param onSuccess is a callback called when the task is successfully executed
  98846. * @param onError is a callback called if an error occurs
  98847. */
  98848. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98849. throw new Error("runTask is not implemented");
  98850. };
  98851. /**
  98852. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  98853. * This can be used with failed tasks that have the reason for failure fixed.
  98854. */
  98855. AbstractAssetTask.prototype.reset = function () {
  98856. this._taskState = AssetTaskState.INIT;
  98857. };
  98858. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  98859. this._taskState = AssetTaskState.ERROR;
  98860. this._errorObject = {
  98861. message: message,
  98862. exception: exception
  98863. };
  98864. if (this.onError) {
  98865. this.onError(this, message, exception);
  98866. }
  98867. onError();
  98868. };
  98869. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  98870. try {
  98871. this._taskState = AssetTaskState.DONE;
  98872. this._isCompleted = true;
  98873. if (this.onSuccess) {
  98874. this.onSuccess(this);
  98875. }
  98876. onSuccess();
  98877. }
  98878. catch (e) {
  98879. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  98880. }
  98881. };
  98882. return AbstractAssetTask;
  98883. }());
  98884. BABYLON.AbstractAssetTask = AbstractAssetTask;
  98885. /**
  98886. * Class used to share progress information about assets loading
  98887. */
  98888. var AssetsProgressEvent = /** @class */ (function () {
  98889. /**
  98890. * Creates a {BABYLON.AssetsProgressEvent}
  98891. * @param remainingCount defines the number of remaining tasks to process
  98892. * @param totalCount defines the total number of tasks
  98893. * @param task defines the task that was just processed
  98894. */
  98895. function AssetsProgressEvent(remainingCount, totalCount, task) {
  98896. this.remainingCount = remainingCount;
  98897. this.totalCount = totalCount;
  98898. this.task = task;
  98899. }
  98900. return AssetsProgressEvent;
  98901. }());
  98902. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  98903. /**
  98904. * Define a task used by {BABYLON.AssetsManager} to load meshes
  98905. */
  98906. var MeshAssetTask = /** @class */ (function (_super) {
  98907. __extends(MeshAssetTask, _super);
  98908. /**
  98909. * Creates a new {BABYLON.MeshAssetTask}
  98910. * @param name defines the name of the task
  98911. * @param meshesNames defines the list of mesh's names you want to load
  98912. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  98913. * @param sceneFilename defines the filename of the scene to load from
  98914. */
  98915. function MeshAssetTask(
  98916. /**
  98917. * Defines the name of the task
  98918. */
  98919. name,
  98920. /**
  98921. * Defines the list of mesh's names you want to load
  98922. */
  98923. meshesNames,
  98924. /**
  98925. * Defines the root url to use as a base to load your meshes and associated resources
  98926. */
  98927. rootUrl,
  98928. /**
  98929. * Defines the filename of the scene to load from
  98930. */
  98931. sceneFilename) {
  98932. var _this = _super.call(this, name) || this;
  98933. _this.name = name;
  98934. _this.meshesNames = meshesNames;
  98935. _this.rootUrl = rootUrl;
  98936. _this.sceneFilename = sceneFilename;
  98937. return _this;
  98938. }
  98939. /**
  98940. * Execute the current task
  98941. * @param scene defines the scene where you want your assets to be loaded
  98942. * @param onSuccess is a callback called when the task is successfully executed
  98943. * @param onError is a callback called if an error occurs
  98944. */
  98945. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98946. var _this = this;
  98947. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  98948. _this.loadedMeshes = meshes;
  98949. _this.loadedParticleSystems = particleSystems;
  98950. _this.loadedSkeletons = skeletons;
  98951. onSuccess();
  98952. }, null, function (scene, message, exception) {
  98953. onError(message, exception);
  98954. });
  98955. };
  98956. return MeshAssetTask;
  98957. }(AbstractAssetTask));
  98958. BABYLON.MeshAssetTask = MeshAssetTask;
  98959. /**
  98960. * Define a task used by {BABYLON.AssetsManager} to load text content
  98961. */
  98962. var TextFileAssetTask = /** @class */ (function (_super) {
  98963. __extends(TextFileAssetTask, _super);
  98964. /**
  98965. * Creates a new TextFileAssetTask object
  98966. * @param name defines the name of the task
  98967. * @param url defines the location of the file to load
  98968. */
  98969. function TextFileAssetTask(
  98970. /**
  98971. * Defines the name of the task
  98972. */
  98973. name,
  98974. /**
  98975. * Defines the location of the file to load
  98976. */
  98977. url) {
  98978. var _this = _super.call(this, name) || this;
  98979. _this.name = name;
  98980. _this.url = url;
  98981. return _this;
  98982. }
  98983. /**
  98984. * Execute the current task
  98985. * @param scene defines the scene where you want your assets to be loaded
  98986. * @param onSuccess is a callback called when the task is successfully executed
  98987. * @param onError is a callback called if an error occurs
  98988. */
  98989. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98990. var _this = this;
  98991. scene._loadFile(this.url, function (data) {
  98992. _this.text = data;
  98993. onSuccess();
  98994. }, undefined, false, false, function (request, exception) {
  98995. if (request) {
  98996. onError(request.status + " " + request.statusText, exception);
  98997. }
  98998. });
  98999. };
  99000. return TextFileAssetTask;
  99001. }(AbstractAssetTask));
  99002. BABYLON.TextFileAssetTask = TextFileAssetTask;
  99003. /**
  99004. * Define a task used by {BABYLON.AssetsManager} to load binary data
  99005. */
  99006. var BinaryFileAssetTask = /** @class */ (function (_super) {
  99007. __extends(BinaryFileAssetTask, _super);
  99008. /**
  99009. * Creates a new BinaryFileAssetTask object
  99010. * @param name defines the name of the new task
  99011. * @param url defines the location of the file to load
  99012. */
  99013. function BinaryFileAssetTask(
  99014. /**
  99015. * Defines the name of the task
  99016. */
  99017. name,
  99018. /**
  99019. * Defines the location of the file to load
  99020. */
  99021. url) {
  99022. var _this = _super.call(this, name) || this;
  99023. _this.name = name;
  99024. _this.url = url;
  99025. return _this;
  99026. }
  99027. /**
  99028. * Execute the current task
  99029. * @param scene defines the scene where you want your assets to be loaded
  99030. * @param onSuccess is a callback called when the task is successfully executed
  99031. * @param onError is a callback called if an error occurs
  99032. */
  99033. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99034. var _this = this;
  99035. scene._loadFile(this.url, function (data) {
  99036. _this.data = data;
  99037. onSuccess();
  99038. }, undefined, true, true, function (request, exception) {
  99039. if (request) {
  99040. onError(request.status + " " + request.statusText, exception);
  99041. }
  99042. });
  99043. };
  99044. return BinaryFileAssetTask;
  99045. }(AbstractAssetTask));
  99046. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  99047. /**
  99048. * Define a task used by {BABYLON.AssetsManager} to load images
  99049. */
  99050. var ImageAssetTask = /** @class */ (function (_super) {
  99051. __extends(ImageAssetTask, _super);
  99052. /**
  99053. * Creates a new ImageAssetTask
  99054. * @param name defines the name of the task
  99055. * @param url defines the location of the image to load
  99056. */
  99057. function ImageAssetTask(
  99058. /**
  99059. * Defines the name of the task
  99060. */
  99061. name,
  99062. /**
  99063. * Defines the location of the image to load
  99064. */
  99065. url) {
  99066. var _this = _super.call(this, name) || this;
  99067. _this.name = name;
  99068. _this.url = url;
  99069. return _this;
  99070. }
  99071. /**
  99072. * Execute the current task
  99073. * @param scene defines the scene where you want your assets to be loaded
  99074. * @param onSuccess is a callback called when the task is successfully executed
  99075. * @param onError is a callback called if an error occurs
  99076. */
  99077. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99078. var _this = this;
  99079. var img = new Image();
  99080. BABYLON.Tools.SetCorsBehavior(this.url, img);
  99081. img.onload = function () {
  99082. _this.image = img;
  99083. onSuccess();
  99084. };
  99085. img.onerror = function (err) {
  99086. onError("Error loading image", err);
  99087. };
  99088. img.src = this.url;
  99089. };
  99090. return ImageAssetTask;
  99091. }(AbstractAssetTask));
  99092. BABYLON.ImageAssetTask = ImageAssetTask;
  99093. /**
  99094. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  99095. */
  99096. var TextureAssetTask = /** @class */ (function (_super) {
  99097. __extends(TextureAssetTask, _super);
  99098. /**
  99099. * Creates a new TextureAssetTask object
  99100. * @param name defines the name of the task
  99101. * @param url defines the location of the file to load
  99102. * @param noMipmap defines if mipmap should not be generated (default is false)
  99103. * @param invertY defines if texture must be inverted on Y axis (default is false)
  99104. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99105. */
  99106. function TextureAssetTask(
  99107. /**
  99108. * Defines the name of the task
  99109. */
  99110. name,
  99111. /**
  99112. * Defines the location of the file to load
  99113. */
  99114. url,
  99115. /**
  99116. * Defines if mipmap should not be generated (default is false)
  99117. */
  99118. noMipmap,
  99119. /**
  99120. * Defines if texture must be inverted on Y axis (default is false)
  99121. */
  99122. invertY,
  99123. /**
  99124. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99125. */
  99126. samplingMode) {
  99127. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99128. var _this = _super.call(this, name) || this;
  99129. _this.name = name;
  99130. _this.url = url;
  99131. _this.noMipmap = noMipmap;
  99132. _this.invertY = invertY;
  99133. _this.samplingMode = samplingMode;
  99134. return _this;
  99135. }
  99136. /**
  99137. * Execute the current task
  99138. * @param scene defines the scene where you want your assets to be loaded
  99139. * @param onSuccess is a callback called when the task is successfully executed
  99140. * @param onError is a callback called if an error occurs
  99141. */
  99142. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99143. var onload = function () {
  99144. onSuccess();
  99145. };
  99146. var onerror = function (message, exception) {
  99147. onError(message, exception);
  99148. };
  99149. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  99150. };
  99151. return TextureAssetTask;
  99152. }(AbstractAssetTask));
  99153. BABYLON.TextureAssetTask = TextureAssetTask;
  99154. /**
  99155. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  99156. */
  99157. var CubeTextureAssetTask = /** @class */ (function (_super) {
  99158. __extends(CubeTextureAssetTask, _super);
  99159. /**
  99160. * Creates a new CubeTextureAssetTask
  99161. * @param name defines the name of the task
  99162. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99163. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99164. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99165. * @param files defines the explicit list of files (undefined by default)
  99166. */
  99167. function CubeTextureAssetTask(
  99168. /**
  99169. * Defines the name of the task
  99170. */
  99171. name,
  99172. /**
  99173. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99174. */
  99175. url,
  99176. /**
  99177. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99178. */
  99179. extensions,
  99180. /**
  99181. * Defines if mipmaps should not be generated (default is false)
  99182. */
  99183. noMipmap,
  99184. /**
  99185. * Defines the explicit list of files (undefined by default)
  99186. */
  99187. files) {
  99188. var _this = _super.call(this, name) || this;
  99189. _this.name = name;
  99190. _this.url = url;
  99191. _this.extensions = extensions;
  99192. _this.noMipmap = noMipmap;
  99193. _this.files = files;
  99194. return _this;
  99195. }
  99196. /**
  99197. * Execute the current task
  99198. * @param scene defines the scene where you want your assets to be loaded
  99199. * @param onSuccess is a callback called when the task is successfully executed
  99200. * @param onError is a callback called if an error occurs
  99201. */
  99202. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99203. var onload = function () {
  99204. onSuccess();
  99205. };
  99206. var onerror = function (message, exception) {
  99207. onError(message, exception);
  99208. };
  99209. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  99210. };
  99211. return CubeTextureAssetTask;
  99212. }(AbstractAssetTask));
  99213. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  99214. /**
  99215. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  99216. */
  99217. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  99218. __extends(HDRCubeTextureAssetTask, _super);
  99219. /**
  99220. * Creates a new HDRCubeTextureAssetTask object
  99221. * @param name defines the name of the task
  99222. * @param url defines the location of the file to load
  99223. * @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.
  99224. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99225. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99226. * @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)
  99227. * @param reserved Internal use only
  99228. */
  99229. function HDRCubeTextureAssetTask(
  99230. /**
  99231. * Defines the name of the task
  99232. */
  99233. name,
  99234. /**
  99235. * Defines the location of the file to load
  99236. */
  99237. url,
  99238. /**
  99239. * Defines the desired size (the more it increases the longer the generation will be)
  99240. */
  99241. size,
  99242. /**
  99243. * Defines if mipmaps should not be generated (default is false)
  99244. */
  99245. noMipmap,
  99246. /**
  99247. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99248. */
  99249. generateHarmonics,
  99250. /**
  99251. * 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)
  99252. */
  99253. gammaSpace,
  99254. /**
  99255. * Internal Use Only
  99256. */
  99257. reserved) {
  99258. if (noMipmap === void 0) { noMipmap = false; }
  99259. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99260. if (gammaSpace === void 0) { gammaSpace = false; }
  99261. if (reserved === void 0) { reserved = false; }
  99262. var _this = _super.call(this, name) || this;
  99263. _this.name = name;
  99264. _this.url = url;
  99265. _this.size = size;
  99266. _this.noMipmap = noMipmap;
  99267. _this.generateHarmonics = generateHarmonics;
  99268. _this.gammaSpace = gammaSpace;
  99269. _this.reserved = reserved;
  99270. return _this;
  99271. }
  99272. /**
  99273. * Execute the current task
  99274. * @param scene defines the scene where you want your assets to be loaded
  99275. * @param onSuccess is a callback called when the task is successfully executed
  99276. * @param onError is a callback called if an error occurs
  99277. */
  99278. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  99279. var onload = function () {
  99280. onSuccess();
  99281. };
  99282. var onerror = function (message, exception) {
  99283. onError(message, exception);
  99284. };
  99285. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  99286. };
  99287. return HDRCubeTextureAssetTask;
  99288. }(AbstractAssetTask));
  99289. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  99290. /**
  99291. * This class can be used to easily import assets into a scene
  99292. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  99293. */
  99294. var AssetsManager = /** @class */ (function () {
  99295. /**
  99296. * Creates a new AssetsManager
  99297. * @param scene defines the scene to work on
  99298. */
  99299. function AssetsManager(scene) {
  99300. this._isLoading = false;
  99301. this._tasks = new Array();
  99302. this._waitingTasksCount = 0;
  99303. this._totalTasksCount = 0;
  99304. /**
  99305. * Observable called when all tasks are processed
  99306. */
  99307. this.onTaskSuccessObservable = new BABYLON.Observable();
  99308. /**
  99309. * Observable called when a task had an error
  99310. */
  99311. this.onTaskErrorObservable = new BABYLON.Observable();
  99312. /**
  99313. * Observable called when a task is successful
  99314. */
  99315. this.onTasksDoneObservable = new BABYLON.Observable();
  99316. /**
  99317. * Observable called when a task is done (whatever the result is)
  99318. */
  99319. this.onProgressObservable = new BABYLON.Observable();
  99320. /**
  99321. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  99322. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  99323. */
  99324. this.useDefaultLoadingScreen = true;
  99325. this._scene = scene;
  99326. }
  99327. /**
  99328. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  99329. * @param taskName defines the name of the new task
  99330. * @param meshesNames defines the name of meshes to load
  99331. * @param rootUrl defines the root url to use to locate files
  99332. * @param sceneFilename defines the filename of the scene file
  99333. * @returns a new {BABYLON.MeshAssetTask} object
  99334. */
  99335. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  99336. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  99337. this._tasks.push(task);
  99338. return task;
  99339. };
  99340. /**
  99341. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  99342. * @param taskName defines the name of the new task
  99343. * @param url defines the url of the file to load
  99344. * @returns a new {BABYLON.TextFileAssetTask} object
  99345. */
  99346. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  99347. var task = new TextFileAssetTask(taskName, url);
  99348. this._tasks.push(task);
  99349. return task;
  99350. };
  99351. /**
  99352. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  99353. * @param taskName defines the name of the new task
  99354. * @param url defines the url of the file to load
  99355. * @returns a new {BABYLON.BinaryFileAssetTask} object
  99356. */
  99357. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  99358. var task = new BinaryFileAssetTask(taskName, url);
  99359. this._tasks.push(task);
  99360. return task;
  99361. };
  99362. /**
  99363. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  99364. * @param taskName defines the name of the new task
  99365. * @param url defines the url of the file to load
  99366. * @returns a new {BABYLON.ImageAssetTask} object
  99367. */
  99368. AssetsManager.prototype.addImageTask = function (taskName, url) {
  99369. var task = new ImageAssetTask(taskName, url);
  99370. this._tasks.push(task);
  99371. return task;
  99372. };
  99373. /**
  99374. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  99375. * @param taskName defines the name of the new task
  99376. * @param url defines the url of the file to load
  99377. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99378. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  99379. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  99380. * @returns a new {BABYLON.TextureAssetTask} object
  99381. */
  99382. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  99383. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99384. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  99385. this._tasks.push(task);
  99386. return task;
  99387. };
  99388. /**
  99389. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  99390. * @param taskName defines the name of the new task
  99391. * @param url defines the url of the file to load
  99392. * @param extensions defines the extension to use to load the cube map (can be null)
  99393. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99394. * @param files defines the list of files to load (can be null)
  99395. * @returns a new {BABYLON.CubeTextureAssetTask} object
  99396. */
  99397. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  99398. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  99399. this._tasks.push(task);
  99400. return task;
  99401. };
  99402. /**
  99403. *
  99404. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  99405. * @param taskName defines the name of the new task
  99406. * @param url defines the url of the file to load
  99407. * @param size defines the size you want for the cubemap (can be null)
  99408. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99409. * @param generateHarmonics defines if you want to automatically generate (true by default)
  99410. * @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)
  99411. * @param reserved Internal use only
  99412. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  99413. */
  99414. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  99415. if (noMipmap === void 0) { noMipmap = false; }
  99416. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99417. if (gammaSpace === void 0) { gammaSpace = false; }
  99418. if (reserved === void 0) { reserved = false; }
  99419. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  99420. this._tasks.push(task);
  99421. return task;
  99422. };
  99423. /**
  99424. * Remove a task from the assets manager.
  99425. * @param task the task to remove
  99426. */
  99427. AssetsManager.prototype.removeTask = function (task) {
  99428. var index = this._tasks.indexOf(task);
  99429. if (index > -1) {
  99430. this._tasks.splice(index, 1);
  99431. }
  99432. };
  99433. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  99434. this._waitingTasksCount--;
  99435. try {
  99436. if (this.onProgress) {
  99437. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  99438. }
  99439. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  99440. }
  99441. catch (e) {
  99442. BABYLON.Tools.Error("Error running progress callbacks.");
  99443. console.log(e);
  99444. }
  99445. if (this._waitingTasksCount === 0) {
  99446. try {
  99447. if (this.onFinish) {
  99448. this.onFinish(this._tasks);
  99449. }
  99450. // Let's remove successfull tasks
  99451. var currentTasks = this._tasks.slice();
  99452. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  99453. var task = currentTasks_1[_i];
  99454. if (task.taskState === AssetTaskState.DONE) {
  99455. var index = this._tasks.indexOf(task);
  99456. if (index > -1) {
  99457. this._tasks.splice(index, 1);
  99458. }
  99459. }
  99460. }
  99461. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99462. }
  99463. catch (e) {
  99464. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  99465. console.log(e);
  99466. }
  99467. this._isLoading = false;
  99468. this._scene.getEngine().hideLoadingUI();
  99469. }
  99470. };
  99471. AssetsManager.prototype._runTask = function (task) {
  99472. var _this = this;
  99473. var done = function () {
  99474. try {
  99475. if (_this.onTaskSuccess) {
  99476. _this.onTaskSuccess(task);
  99477. }
  99478. _this.onTaskSuccessObservable.notifyObservers(task);
  99479. _this._decreaseWaitingTasksCount(task);
  99480. }
  99481. catch (e) {
  99482. error("Error executing task success callbacks", e);
  99483. }
  99484. };
  99485. var error = function (message, exception) {
  99486. task._setErrorObject(message, exception);
  99487. if (_this.onTaskError) {
  99488. _this.onTaskError(task);
  99489. }
  99490. _this.onTaskErrorObservable.notifyObservers(task);
  99491. _this._decreaseWaitingTasksCount(task);
  99492. };
  99493. task.run(this._scene, done, error);
  99494. };
  99495. /**
  99496. * Reset the {BABYLON.AssetsManager} and remove all tasks
  99497. * @return the current instance of the {BABYLON.AssetsManager}
  99498. */
  99499. AssetsManager.prototype.reset = function () {
  99500. this._isLoading = false;
  99501. this._tasks = new Array();
  99502. return this;
  99503. };
  99504. /**
  99505. * Start the loading process
  99506. * @return the current instance of the {BABYLON.AssetsManager}
  99507. */
  99508. AssetsManager.prototype.load = function () {
  99509. if (this._isLoading) {
  99510. return this;
  99511. }
  99512. this._isLoading = true;
  99513. this._waitingTasksCount = this._tasks.length;
  99514. this._totalTasksCount = this._tasks.length;
  99515. if (this._waitingTasksCount === 0) {
  99516. this._isLoading = false;
  99517. if (this.onFinish) {
  99518. this.onFinish(this._tasks);
  99519. }
  99520. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99521. return this;
  99522. }
  99523. if (this.useDefaultLoadingScreen) {
  99524. this._scene.getEngine().displayLoadingUI();
  99525. }
  99526. for (var index = 0; index < this._tasks.length; index++) {
  99527. var task = this._tasks[index];
  99528. if (task.taskState === AssetTaskState.INIT) {
  99529. this._runTask(task);
  99530. }
  99531. }
  99532. return this;
  99533. };
  99534. return AssetsManager;
  99535. }());
  99536. BABYLON.AssetsManager = AssetsManager;
  99537. })(BABYLON || (BABYLON = {}));
  99538. //# sourceMappingURL=babylon.assetsManager.js.map
  99539. var BABYLON;
  99540. (function (BABYLON) {
  99541. var serializedGeometries = [];
  99542. var serializeGeometry = function (geometry, serializationGeometries) {
  99543. if (serializedGeometries[geometry.id]) {
  99544. return;
  99545. }
  99546. if (geometry.doNotSerialize) {
  99547. return;
  99548. }
  99549. if (geometry instanceof BABYLON.BoxGeometry) {
  99550. serializationGeometries.boxes.push(geometry.serialize());
  99551. }
  99552. else if (geometry instanceof BABYLON.SphereGeometry) {
  99553. serializationGeometries.spheres.push(geometry.serialize());
  99554. }
  99555. else if (geometry instanceof BABYLON.CylinderGeometry) {
  99556. serializationGeometries.cylinders.push(geometry.serialize());
  99557. }
  99558. else if (geometry instanceof BABYLON.TorusGeometry) {
  99559. serializationGeometries.toruses.push(geometry.serialize());
  99560. }
  99561. else if (geometry instanceof BABYLON.GroundGeometry) {
  99562. serializationGeometries.grounds.push(geometry.serialize());
  99563. }
  99564. else if (geometry instanceof BABYLON.Plane) {
  99565. serializationGeometries.planes.push(geometry.serialize());
  99566. }
  99567. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  99568. serializationGeometries.torusKnots.push(geometry.serialize());
  99569. }
  99570. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  99571. throw new Error("Unknown primitive type");
  99572. }
  99573. else {
  99574. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  99575. }
  99576. serializedGeometries[geometry.id] = true;
  99577. };
  99578. var serializeMesh = function (mesh, serializationScene) {
  99579. var serializationObject = {};
  99580. // Geometry
  99581. var geometry = mesh._geometry;
  99582. if (geometry) {
  99583. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  99584. // 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
  99585. serializeGeometry(geometry, serializationScene.geometries);
  99586. }
  99587. }
  99588. // Custom
  99589. if (mesh.serialize) {
  99590. mesh.serialize(serializationObject);
  99591. }
  99592. return serializationObject;
  99593. };
  99594. var finalizeSingleMesh = function (mesh, serializationObject) {
  99595. //only works if the mesh is already loaded
  99596. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99597. //serialize material
  99598. if (mesh.material) {
  99599. if (mesh.material instanceof BABYLON.MultiMaterial) {
  99600. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  99601. serializationObject.materials = serializationObject.materials || [];
  99602. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99603. serializationObject.multiMaterials.push(mesh.material.serialize());
  99604. var _loop_1 = function (submaterial) {
  99605. if (submaterial) {
  99606. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  99607. serializationObject.materials.push(submaterial.serialize());
  99608. }
  99609. }
  99610. };
  99611. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  99612. var submaterial = _a[_i];
  99613. _loop_1(submaterial);
  99614. }
  99615. }
  99616. }
  99617. else {
  99618. serializationObject.materials = serializationObject.materials || [];
  99619. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99620. serializationObject.materials.push(mesh.material.serialize());
  99621. }
  99622. }
  99623. }
  99624. //serialize geometry
  99625. var geometry = mesh._geometry;
  99626. if (geometry) {
  99627. if (!serializationObject.geometries) {
  99628. serializationObject.geometries = {};
  99629. serializationObject.geometries.boxes = [];
  99630. serializationObject.geometries.spheres = [];
  99631. serializationObject.geometries.cylinders = [];
  99632. serializationObject.geometries.toruses = [];
  99633. serializationObject.geometries.grounds = [];
  99634. serializationObject.geometries.planes = [];
  99635. serializationObject.geometries.torusKnots = [];
  99636. serializationObject.geometries.vertexData = [];
  99637. }
  99638. serializeGeometry(geometry, serializationObject.geometries);
  99639. }
  99640. // Skeletons
  99641. if (mesh.skeleton) {
  99642. serializationObject.skeletons = serializationObject.skeletons || [];
  99643. serializationObject.skeletons.push(mesh.skeleton.serialize());
  99644. }
  99645. //serialize the actual mesh
  99646. serializationObject.meshes = serializationObject.meshes || [];
  99647. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99648. }
  99649. };
  99650. var SceneSerializer = /** @class */ (function () {
  99651. function SceneSerializer() {
  99652. }
  99653. SceneSerializer.ClearCache = function () {
  99654. serializedGeometries = [];
  99655. };
  99656. SceneSerializer.Serialize = function (scene) {
  99657. var serializationObject = {};
  99658. SceneSerializer.ClearCache();
  99659. // Scene
  99660. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  99661. serializationObject.autoClear = scene.autoClear;
  99662. serializationObject.clearColor = scene.clearColor.asArray();
  99663. serializationObject.ambientColor = scene.ambientColor.asArray();
  99664. serializationObject.gravity = scene.gravity.asArray();
  99665. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  99666. serializationObject.workerCollisions = scene.workerCollisions;
  99667. // Fog
  99668. if (scene.fogMode && scene.fogMode !== 0) {
  99669. serializationObject.fogMode = scene.fogMode;
  99670. serializationObject.fogColor = scene.fogColor.asArray();
  99671. serializationObject.fogStart = scene.fogStart;
  99672. serializationObject.fogEnd = scene.fogEnd;
  99673. serializationObject.fogDensity = scene.fogDensity;
  99674. }
  99675. //Physics
  99676. if (scene.isPhysicsEnabled()) {
  99677. var physicEngine = scene.getPhysicsEngine();
  99678. if (physicEngine) {
  99679. serializationObject.physicsEnabled = true;
  99680. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  99681. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  99682. }
  99683. }
  99684. // Metadata
  99685. if (scene.metadata) {
  99686. serializationObject.metadata = scene.metadata;
  99687. }
  99688. // Morph targets
  99689. serializationObject.morphTargetManagers = [];
  99690. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  99691. var abstractMesh = _a[_i];
  99692. var manager = abstractMesh.morphTargetManager;
  99693. if (manager) {
  99694. serializationObject.morphTargetManagers.push(manager.serialize());
  99695. }
  99696. }
  99697. // Lights
  99698. serializationObject.lights = [];
  99699. var index;
  99700. var light;
  99701. for (index = 0; index < scene.lights.length; index++) {
  99702. light = scene.lights[index];
  99703. if (!light.doNotSerialize) {
  99704. serializationObject.lights.push(light.serialize());
  99705. }
  99706. }
  99707. // Cameras
  99708. serializationObject.cameras = [];
  99709. for (index = 0; index < scene.cameras.length; index++) {
  99710. var camera = scene.cameras[index];
  99711. if (!camera.doNotSerialize) {
  99712. serializationObject.cameras.push(camera.serialize());
  99713. }
  99714. }
  99715. if (scene.activeCamera) {
  99716. serializationObject.activeCameraID = scene.activeCamera.id;
  99717. }
  99718. // Animations
  99719. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  99720. // Materials
  99721. serializationObject.materials = [];
  99722. serializationObject.multiMaterials = [];
  99723. var material;
  99724. for (index = 0; index < scene.materials.length; index++) {
  99725. material = scene.materials[index];
  99726. if (!material.doNotSerialize) {
  99727. serializationObject.materials.push(material.serialize());
  99728. }
  99729. }
  99730. // MultiMaterials
  99731. serializationObject.multiMaterials = [];
  99732. for (index = 0; index < scene.multiMaterials.length; index++) {
  99733. var multiMaterial = scene.multiMaterials[index];
  99734. serializationObject.multiMaterials.push(multiMaterial.serialize());
  99735. }
  99736. // Environment texture
  99737. if (scene.environmentTexture) {
  99738. serializationObject.environmentTexture = scene.environmentTexture.name;
  99739. }
  99740. // Skeletons
  99741. serializationObject.skeletons = [];
  99742. for (index = 0; index < scene.skeletons.length; index++) {
  99743. var skeleton = scene.skeletons[index];
  99744. if (!skeleton.doNotSerialize) {
  99745. serializationObject.skeletons.push(skeleton.serialize());
  99746. }
  99747. }
  99748. // Transform nodes
  99749. serializationObject.transformNodes = [];
  99750. for (index = 0; index < scene.transformNodes.length; index++) {
  99751. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  99752. }
  99753. // Geometries
  99754. serializationObject.geometries = {};
  99755. serializationObject.geometries.boxes = [];
  99756. serializationObject.geometries.spheres = [];
  99757. serializationObject.geometries.cylinders = [];
  99758. serializationObject.geometries.toruses = [];
  99759. serializationObject.geometries.grounds = [];
  99760. serializationObject.geometries.planes = [];
  99761. serializationObject.geometries.torusKnots = [];
  99762. serializationObject.geometries.vertexData = [];
  99763. serializedGeometries = [];
  99764. var geometries = scene.getGeometries();
  99765. for (index = 0; index < geometries.length; index++) {
  99766. var geometry = geometries[index];
  99767. if (geometry.isReady()) {
  99768. serializeGeometry(geometry, serializationObject.geometries);
  99769. }
  99770. }
  99771. // Meshes
  99772. serializationObject.meshes = [];
  99773. for (index = 0; index < scene.meshes.length; index++) {
  99774. var abstractMesh = scene.meshes[index];
  99775. if (abstractMesh instanceof BABYLON.Mesh) {
  99776. var mesh = abstractMesh;
  99777. if (!mesh.doNotSerialize) {
  99778. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99779. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99780. }
  99781. }
  99782. }
  99783. }
  99784. // Particles Systems
  99785. serializationObject.particleSystems = [];
  99786. for (index = 0; index < scene.particleSystems.length; index++) {
  99787. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  99788. }
  99789. // Shadows
  99790. serializationObject.shadowGenerators = [];
  99791. for (index = 0; index < scene.lights.length; index++) {
  99792. light = scene.lights[index];
  99793. var shadowGenerator = light.getShadowGenerator();
  99794. if (shadowGenerator) {
  99795. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  99796. }
  99797. }
  99798. // Action Manager
  99799. if (scene.actionManager) {
  99800. serializationObject.actions = scene.actionManager.serialize("scene");
  99801. }
  99802. // Audio
  99803. serializationObject.sounds = [];
  99804. for (index = 0; index < scene.soundTracks.length; index++) {
  99805. var soundtrack = scene.soundTracks[index];
  99806. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  99807. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  99808. }
  99809. }
  99810. // Components
  99811. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  99812. var component = _c[_b];
  99813. component.serialize(serializationObject);
  99814. }
  99815. return serializationObject;
  99816. };
  99817. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  99818. if (withParents === void 0) { withParents = false; }
  99819. if (withChildren === void 0) { withChildren = false; }
  99820. var serializationObject = {};
  99821. SceneSerializer.ClearCache();
  99822. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  99823. if (withParents || withChildren) {
  99824. //deliberate for loop! not for each, appended should be processed as well.
  99825. for (var i = 0; i < toSerialize.length; ++i) {
  99826. if (withChildren) {
  99827. toSerialize[i].getDescendants().forEach(function (node) {
  99828. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  99829. toSerialize.push(node);
  99830. }
  99831. });
  99832. }
  99833. //make sure the array doesn't contain the object already
  99834. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  99835. toSerialize.push(toSerialize[i].parent);
  99836. }
  99837. }
  99838. }
  99839. toSerialize.forEach(function (mesh) {
  99840. finalizeSingleMesh(mesh, serializationObject);
  99841. });
  99842. return serializationObject;
  99843. };
  99844. return SceneSerializer;
  99845. }());
  99846. BABYLON.SceneSerializer = SceneSerializer;
  99847. })(BABYLON || (BABYLON = {}));
  99848. //# sourceMappingURL=babylon.sceneSerializer.js.map
  99849. var BABYLON;
  99850. (function (BABYLON) {
  99851. var ReflectionProbe = /** @class */ (function () {
  99852. function ReflectionProbe(name, size, scene, generateMipMaps) {
  99853. if (generateMipMaps === void 0) { generateMipMaps = true; }
  99854. var _this = this;
  99855. this.name = name;
  99856. this._viewMatrix = BABYLON.Matrix.Identity();
  99857. this._target = BABYLON.Vector3.Zero();
  99858. this._add = BABYLON.Vector3.Zero();
  99859. this._invertYAxis = false;
  99860. this.position = BABYLON.Vector3.Zero();
  99861. this._scene = scene;
  99862. this._scene.reflectionProbes.push(this);
  99863. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  99864. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  99865. switch (faceIndex) {
  99866. case 0:
  99867. _this._add.copyFromFloats(1, 0, 0);
  99868. break;
  99869. case 1:
  99870. _this._add.copyFromFloats(-1, 0, 0);
  99871. break;
  99872. case 2:
  99873. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  99874. break;
  99875. case 3:
  99876. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  99877. break;
  99878. case 4:
  99879. _this._add.copyFromFloats(0, 0, 1);
  99880. break;
  99881. case 5:
  99882. _this._add.copyFromFloats(0, 0, -1);
  99883. break;
  99884. }
  99885. if (_this._attachedMesh) {
  99886. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  99887. }
  99888. _this.position.addToRef(_this._add, _this._target);
  99889. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  99890. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  99891. scene._forcedViewPosition = _this.position;
  99892. });
  99893. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  99894. scene._forcedViewPosition = null;
  99895. scene.updateTransformMatrix(true);
  99896. });
  99897. if (scene.activeCamera) {
  99898. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  99899. }
  99900. }
  99901. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  99902. get: function () {
  99903. return this._renderTargetTexture.samples;
  99904. },
  99905. set: function (value) {
  99906. this._renderTargetTexture.samples = value;
  99907. },
  99908. enumerable: true,
  99909. configurable: true
  99910. });
  99911. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  99912. get: function () {
  99913. return this._renderTargetTexture.refreshRate;
  99914. },
  99915. set: function (value) {
  99916. this._renderTargetTexture.refreshRate = value;
  99917. },
  99918. enumerable: true,
  99919. configurable: true
  99920. });
  99921. ReflectionProbe.prototype.getScene = function () {
  99922. return this._scene;
  99923. };
  99924. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  99925. get: function () {
  99926. return this._renderTargetTexture;
  99927. },
  99928. enumerable: true,
  99929. configurable: true
  99930. });
  99931. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  99932. get: function () {
  99933. return this._renderTargetTexture.renderList;
  99934. },
  99935. enumerable: true,
  99936. configurable: true
  99937. });
  99938. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  99939. this._attachedMesh = mesh;
  99940. };
  99941. /**
  99942. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  99943. *
  99944. * @param renderingGroupId The rendering group id corresponding to its index
  99945. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  99946. */
  99947. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  99948. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  99949. };
  99950. ReflectionProbe.prototype.dispose = function () {
  99951. var index = this._scene.reflectionProbes.indexOf(this);
  99952. if (index !== -1) {
  99953. // Remove from the scene if found
  99954. this._scene.reflectionProbes.splice(index, 1);
  99955. }
  99956. if (this._renderTargetTexture) {
  99957. this._renderTargetTexture.dispose();
  99958. this._renderTargetTexture = null;
  99959. }
  99960. };
  99961. return ReflectionProbe;
  99962. }());
  99963. BABYLON.ReflectionProbe = ReflectionProbe;
  99964. })(BABYLON || (BABYLON = {}));
  99965. //# sourceMappingURL=babylon.reflectionProbe.js.map
  99966. var BABYLON;
  99967. (function (BABYLON) {
  99968. /**
  99969. * Defines the layer scene component responsible to manage any layers
  99970. * in a given scene.
  99971. */
  99972. var LayerSceneComponent = /** @class */ (function () {
  99973. /**
  99974. * Creates a new instance of the component for the given scene
  99975. * @param scene Defines the scene to register the component in
  99976. */
  99977. function LayerSceneComponent(scene) {
  99978. /**
  99979. * The component name helpfull to identify the component in the list of scene components.
  99980. */
  99981. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  99982. this.scene = scene;
  99983. this._engine = scene.getEngine();
  99984. scene.layers = new Array();
  99985. }
  99986. /**
  99987. * Registers the component in a given scene
  99988. */
  99989. LayerSceneComponent.prototype.register = function () {
  99990. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  99991. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  99992. };
  99993. /**
  99994. * Rebuilds the elements related to this component in case of
  99995. * context lost for instance.
  99996. */
  99997. LayerSceneComponent.prototype.rebuild = function () {
  99998. var layers = this.scene.layers;
  99999. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  100000. var layer = layers_1[_i];
  100001. layer._rebuild();
  100002. }
  100003. };
  100004. /**
  100005. * Disposes the component and the associated ressources.
  100006. */
  100007. LayerSceneComponent.prototype.dispose = function () {
  100008. var layers = this.scene.layers;
  100009. while (layers.length) {
  100010. layers[0].dispose();
  100011. }
  100012. };
  100013. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  100014. var layers = this.scene.layers;
  100015. if (layers.length) {
  100016. this._engine.setDepthBuffer(false);
  100017. var cameraLayerMask = camera.layerMask;
  100018. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  100019. var layer = layers_2[_i];
  100020. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  100021. layer.render();
  100022. }
  100023. }
  100024. this._engine.setDepthBuffer(true);
  100025. }
  100026. };
  100027. LayerSceneComponent.prototype._drawBackground = function (camera) {
  100028. this._draw(camera, true);
  100029. };
  100030. LayerSceneComponent.prototype._drawForeground = function (camera) {
  100031. this._draw(camera, false);
  100032. };
  100033. return LayerSceneComponent;
  100034. }());
  100035. BABYLON.LayerSceneComponent = LayerSceneComponent;
  100036. })(BABYLON || (BABYLON = {}));
  100037. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  100038. var BABYLON;
  100039. (function (BABYLON) {
  100040. var Layer = /** @class */ (function () {
  100041. function Layer(name, imgUrl, scene, isBackground, color) {
  100042. this.name = name;
  100043. this.scale = new BABYLON.Vector2(1, 1);
  100044. this.offset = new BABYLON.Vector2(0, 0);
  100045. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  100046. this.layerMask = 0x0FFFFFFF;
  100047. this._vertexBuffers = {};
  100048. // Events
  100049. /**
  100050. * An event triggered when the layer is disposed.
  100051. */
  100052. this.onDisposeObservable = new BABYLON.Observable();
  100053. /**
  100054. * An event triggered before rendering the scene
  100055. */
  100056. this.onBeforeRenderObservable = new BABYLON.Observable();
  100057. /**
  100058. * An event triggered after rendering the scene
  100059. */
  100060. this.onAfterRenderObservable = new BABYLON.Observable();
  100061. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  100062. this.isBackground = isBackground === undefined ? true : isBackground;
  100063. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  100064. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  100065. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  100066. if (!layerComponent) {
  100067. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  100068. this._scene._addComponent(layerComponent);
  100069. }
  100070. this._scene.layers.push(this);
  100071. var engine = this._scene.getEngine();
  100072. // VBO
  100073. var vertices = [];
  100074. vertices.push(1, 1);
  100075. vertices.push(-1, 1);
  100076. vertices.push(-1, -1);
  100077. vertices.push(1, -1);
  100078. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  100079. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  100080. this._createIndexBuffer();
  100081. // Effects
  100082. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  100083. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  100084. }
  100085. Object.defineProperty(Layer.prototype, "onDispose", {
  100086. set: function (callback) {
  100087. if (this._onDisposeObserver) {
  100088. this.onDisposeObservable.remove(this._onDisposeObserver);
  100089. }
  100090. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  100091. },
  100092. enumerable: true,
  100093. configurable: true
  100094. });
  100095. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  100096. set: function (callback) {
  100097. if (this._onBeforeRenderObserver) {
  100098. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  100099. }
  100100. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  100101. },
  100102. enumerable: true,
  100103. configurable: true
  100104. });
  100105. Object.defineProperty(Layer.prototype, "onAfterRender", {
  100106. set: function (callback) {
  100107. if (this._onAfterRenderObserver) {
  100108. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100109. }
  100110. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  100111. },
  100112. enumerable: true,
  100113. configurable: true
  100114. });
  100115. Layer.prototype._createIndexBuffer = function () {
  100116. var engine = this._scene.getEngine();
  100117. // Indices
  100118. var indices = [];
  100119. indices.push(0);
  100120. indices.push(1);
  100121. indices.push(2);
  100122. indices.push(0);
  100123. indices.push(2);
  100124. indices.push(3);
  100125. this._indexBuffer = engine.createIndexBuffer(indices);
  100126. };
  100127. Layer.prototype._rebuild = function () {
  100128. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100129. if (vb) {
  100130. vb._rebuild();
  100131. }
  100132. this._createIndexBuffer();
  100133. };
  100134. Layer.prototype.render = function () {
  100135. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  100136. // Check
  100137. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  100138. return;
  100139. var engine = this._scene.getEngine();
  100140. this.onBeforeRenderObservable.notifyObservers(this);
  100141. // Render
  100142. engine.enableEffect(currentEffect);
  100143. engine.setState(false);
  100144. // Texture
  100145. currentEffect.setTexture("textureSampler", this.texture);
  100146. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  100147. // Color
  100148. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  100149. // Scale / offset
  100150. currentEffect.setVector2("offset", this.offset);
  100151. currentEffect.setVector2("scale", this.scale);
  100152. // VBOs
  100153. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  100154. // Draw order
  100155. if (!this.alphaTest) {
  100156. engine.setAlphaMode(this.alphaBlendingMode);
  100157. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100158. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  100159. }
  100160. else {
  100161. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100162. }
  100163. this.onAfterRenderObservable.notifyObservers(this);
  100164. };
  100165. Layer.prototype.dispose = function () {
  100166. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100167. if (vertexBuffer) {
  100168. vertexBuffer.dispose();
  100169. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  100170. }
  100171. if (this._indexBuffer) {
  100172. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  100173. this._indexBuffer = null;
  100174. }
  100175. if (this.texture) {
  100176. this.texture.dispose();
  100177. this.texture = null;
  100178. }
  100179. // Remove from scene
  100180. var index = this._scene.layers.indexOf(this);
  100181. this._scene.layers.splice(index, 1);
  100182. // Callback
  100183. this.onDisposeObservable.notifyObservers(this);
  100184. this.onDisposeObservable.clear();
  100185. this.onAfterRenderObservable.clear();
  100186. this.onBeforeRenderObservable.clear();
  100187. };
  100188. return Layer;
  100189. }());
  100190. BABYLON.Layer = Layer;
  100191. })(BABYLON || (BABYLON = {}));
  100192. //# sourceMappingURL=babylon.layer.js.map
  100193. var BABYLON;
  100194. (function (BABYLON) {
  100195. var TextureTools = /** @class */ (function () {
  100196. function TextureTools() {
  100197. }
  100198. /**
  100199. * Uses the GPU to create a copy texture rescaled at a given size
  100200. * @param texture Texture to copy from
  100201. * @param width Desired width
  100202. * @param height Desired height
  100203. * @return Generated texture
  100204. */
  100205. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  100206. if (useBilinearMode === void 0) { useBilinearMode = true; }
  100207. var scene = texture.getScene();
  100208. var engine = scene.getEngine();
  100209. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  100210. rtt.wrapU = texture.wrapU;
  100211. rtt.wrapV = texture.wrapV;
  100212. rtt.uOffset = texture.uOffset;
  100213. rtt.vOffset = texture.vOffset;
  100214. rtt.uScale = texture.uScale;
  100215. rtt.vScale = texture.vScale;
  100216. rtt.uAng = texture.uAng;
  100217. rtt.vAng = texture.vAng;
  100218. rtt.wAng = texture.wAng;
  100219. rtt.coordinatesIndex = texture.coordinatesIndex;
  100220. rtt.level = texture.level;
  100221. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  100222. rtt._texture.isReady = false;
  100223. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100224. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100225. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  100226. passPostProcess.getEffect().executeWhenCompiled(function () {
  100227. passPostProcess.onApply = function (effect) {
  100228. effect.setTexture("textureSampler", texture);
  100229. };
  100230. var internalTexture = rtt.getInternalTexture();
  100231. if (internalTexture) {
  100232. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  100233. engine.unBindFramebuffer(internalTexture);
  100234. rtt.disposeFramebufferObjects();
  100235. passPostProcess.dispose();
  100236. internalTexture.isReady = true;
  100237. }
  100238. });
  100239. return rtt;
  100240. };
  100241. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  100242. if (!scene._environmentBRDFTexture) {
  100243. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100244. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100245. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100246. scene._environmentBRDFTexture = texture;
  100247. }
  100248. return scene._environmentBRDFTexture;
  100249. };
  100250. 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=";
  100251. return TextureTools;
  100252. }());
  100253. BABYLON.TextureTools = TextureTools;
  100254. })(BABYLON || (BABYLON = {}));
  100255. //# sourceMappingURL=babylon.textureTools.js.map
  100256. var BABYLON;
  100257. (function (BABYLON) {
  100258. var FramingBehavior = /** @class */ (function () {
  100259. function FramingBehavior() {
  100260. this._mode = FramingBehavior.FitFrustumSidesMode;
  100261. this._radiusScale = 1.0;
  100262. this._positionScale = 0.5;
  100263. this._defaultElevation = 0.3;
  100264. this._elevationReturnTime = 1500;
  100265. this._elevationReturnWaitTime = 1000;
  100266. this._zoomStopsAnimation = false;
  100267. this._framingTime = 1500;
  100268. this._isPointerDown = false;
  100269. this._lastInteractionTime = -Infinity;
  100270. // Framing control
  100271. this._animatables = new Array();
  100272. this._betaIsAnimating = false;
  100273. }
  100274. Object.defineProperty(FramingBehavior.prototype, "name", {
  100275. get: function () {
  100276. return "Framing";
  100277. },
  100278. enumerable: true,
  100279. configurable: true
  100280. });
  100281. Object.defineProperty(FramingBehavior.prototype, "mode", {
  100282. /**
  100283. * Gets current mode used by the behavior.
  100284. */
  100285. get: function () {
  100286. return this._mode;
  100287. },
  100288. /**
  100289. * Sets the current mode used by the behavior
  100290. */
  100291. set: function (mode) {
  100292. this._mode = mode;
  100293. },
  100294. enumerable: true,
  100295. configurable: true
  100296. });
  100297. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  100298. /**
  100299. * Gets the scale applied to the radius
  100300. */
  100301. get: function () {
  100302. return this._radiusScale;
  100303. },
  100304. /**
  100305. * Sets the scale applied to the radius (1 by default)
  100306. */
  100307. set: function (radius) {
  100308. this._radiusScale = radius;
  100309. },
  100310. enumerable: true,
  100311. configurable: true
  100312. });
  100313. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  100314. /**
  100315. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100316. */
  100317. get: function () {
  100318. return this._positionScale;
  100319. },
  100320. /**
  100321. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100322. */
  100323. set: function (scale) {
  100324. this._positionScale = scale;
  100325. },
  100326. enumerable: true,
  100327. configurable: true
  100328. });
  100329. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  100330. /**
  100331. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100332. * behaviour is triggered, in radians.
  100333. */
  100334. get: function () {
  100335. return this._defaultElevation;
  100336. },
  100337. /**
  100338. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100339. * behaviour is triggered, in radians.
  100340. */
  100341. set: function (elevation) {
  100342. this._defaultElevation = elevation;
  100343. },
  100344. enumerable: true,
  100345. configurable: true
  100346. });
  100347. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  100348. /**
  100349. * Gets the time (in milliseconds) taken to return to the default beta position.
  100350. * Negative value indicates camera should not return to default.
  100351. */
  100352. get: function () {
  100353. return this._elevationReturnTime;
  100354. },
  100355. /**
  100356. * Sets the time (in milliseconds) taken to return to the default beta position.
  100357. * Negative value indicates camera should not return to default.
  100358. */
  100359. set: function (speed) {
  100360. this._elevationReturnTime = speed;
  100361. },
  100362. enumerable: true,
  100363. configurable: true
  100364. });
  100365. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  100366. /**
  100367. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  100368. */
  100369. get: function () {
  100370. return this._elevationReturnWaitTime;
  100371. },
  100372. /**
  100373. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  100374. */
  100375. set: function (time) {
  100376. this._elevationReturnWaitTime = time;
  100377. },
  100378. enumerable: true,
  100379. configurable: true
  100380. });
  100381. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  100382. /**
  100383. * Gets the flag that indicates if user zooming should stop animation.
  100384. */
  100385. get: function () {
  100386. return this._zoomStopsAnimation;
  100387. },
  100388. /**
  100389. * Sets the flag that indicates if user zooming should stop animation.
  100390. */
  100391. set: function (flag) {
  100392. this._zoomStopsAnimation = flag;
  100393. },
  100394. enumerable: true,
  100395. configurable: true
  100396. });
  100397. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  100398. /**
  100399. * Gets the transition time when framing the mesh, in milliseconds
  100400. */
  100401. get: function () {
  100402. return this._framingTime;
  100403. },
  100404. /**
  100405. * Sets the transition time when framing the mesh, in milliseconds
  100406. */
  100407. set: function (time) {
  100408. this._framingTime = time;
  100409. },
  100410. enumerable: true,
  100411. configurable: true
  100412. });
  100413. FramingBehavior.prototype.init = function () {
  100414. // Do notihng
  100415. };
  100416. FramingBehavior.prototype.attach = function (camera) {
  100417. var _this = this;
  100418. this._attachedCamera = camera;
  100419. var scene = this._attachedCamera.getScene();
  100420. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  100421. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100422. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100423. _this._isPointerDown = true;
  100424. return;
  100425. }
  100426. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100427. _this._isPointerDown = false;
  100428. }
  100429. });
  100430. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100431. if (mesh) {
  100432. _this.zoomOnMesh(mesh);
  100433. }
  100434. });
  100435. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100436. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100437. _this._applyUserInteraction();
  100438. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  100439. // back to the default position after a given timeout
  100440. _this._maintainCameraAboveGround();
  100441. });
  100442. };
  100443. FramingBehavior.prototype.detach = function () {
  100444. if (!this._attachedCamera) {
  100445. return;
  100446. }
  100447. var scene = this._attachedCamera.getScene();
  100448. if (this._onPrePointerObservableObserver) {
  100449. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100450. }
  100451. if (this._onAfterCheckInputsObserver) {
  100452. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100453. }
  100454. if (this._onMeshTargetChangedObserver) {
  100455. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100456. }
  100457. this._attachedCamera = null;
  100458. };
  100459. /**
  100460. * Targets the given mesh and updates zoom level accordingly.
  100461. * @param mesh The mesh to target.
  100462. * @param radius Optional. If a cached radius position already exists, overrides default.
  100463. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100464. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100465. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100466. */
  100467. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  100468. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100469. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100470. mesh.computeWorldMatrix(true);
  100471. var boundingBox = mesh.getBoundingInfo().boundingBox;
  100472. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  100473. };
  100474. /**
  100475. * Targets the given mesh with its children and updates zoom level accordingly.
  100476. * @param mesh The mesh to target.
  100477. * @param radius Optional. If a cached radius position already exists, overrides default.
  100478. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100479. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100480. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100481. */
  100482. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  100483. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100484. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100485. mesh.computeWorldMatrix(true);
  100486. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  100487. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  100488. };
  100489. /**
  100490. * Targets the given meshes with their children and updates zoom level accordingly.
  100491. * @param meshes The mesh to target.
  100492. * @param radius Optional. If a cached radius position already exists, overrides default.
  100493. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100494. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100495. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100496. */
  100497. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  100498. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100499. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100500. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  100501. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  100502. for (var i = 0; i < meshes.length; i++) {
  100503. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  100504. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  100505. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  100506. }
  100507. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  100508. };
  100509. /**
  100510. * Targets the given mesh and updates zoom level accordingly.
  100511. * @param mesh The mesh to target.
  100512. * @param radius Optional. If a cached radius position already exists, overrides default.
  100513. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100514. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100515. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100516. */
  100517. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  100518. var _this = this;
  100519. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100520. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100521. var zoomTarget;
  100522. if (!this._attachedCamera) {
  100523. return;
  100524. }
  100525. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  100526. var bottom = minimumWorld.y;
  100527. var top = maximumWorld.y;
  100528. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  100529. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  100530. if (focusOnOriginXZ) {
  100531. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  100532. }
  100533. else {
  100534. var centerWorld = minimumWorld.add(radiusWorld);
  100535. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  100536. }
  100537. if (!this._vectorTransition) {
  100538. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  100539. }
  100540. this._betaIsAnimating = true;
  100541. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  100542. if (animatable) {
  100543. this._animatables.push(animatable);
  100544. }
  100545. // sets the radius and lower radius bounds
  100546. // Small delta ensures camera is not always at lower zoom limit.
  100547. var radius = 0;
  100548. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  100549. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100550. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  100551. radius = position;
  100552. }
  100553. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100554. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100555. if (this._attachedCamera.lowerRadiusLimit === null) {
  100556. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  100557. }
  100558. }
  100559. // Set sensibilities
  100560. var extend = maximumWorld.subtract(minimumWorld).length();
  100561. this._attachedCamera.panningSensibility = 5000 / extend;
  100562. this._attachedCamera.wheelPrecision = 100 / radius;
  100563. // transition to new radius
  100564. if (!this._radiusTransition) {
  100565. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100566. }
  100567. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  100568. _this.stopAllAnimations();
  100569. if (onAnimationEnd) {
  100570. onAnimationEnd();
  100571. }
  100572. if (_this._attachedCamera) {
  100573. _this._attachedCamera.storeState();
  100574. }
  100575. });
  100576. if (animatable) {
  100577. this._animatables.push(animatable);
  100578. }
  100579. };
  100580. /**
  100581. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  100582. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  100583. * frustum width.
  100584. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  100585. * to fully enclose the mesh in the viewing frustum.
  100586. */
  100587. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  100588. var size = maximumWorld.subtract(minimumWorld);
  100589. var boxVectorGlobalDiagonal = size.length();
  100590. var frustumSlope = this._getFrustumSlope();
  100591. // Formula for setting distance
  100592. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  100593. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  100594. // Horizon distance
  100595. var radius = radiusWithoutFraming * this._radiusScale;
  100596. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  100597. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  100598. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  100599. var camera = this._attachedCamera;
  100600. if (!camera) {
  100601. return 0;
  100602. }
  100603. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100604. // Don't exceed the requested limit
  100605. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  100606. }
  100607. // Don't exceed the upper radius limit
  100608. if (camera.upperRadiusLimit) {
  100609. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  100610. }
  100611. return distance;
  100612. };
  100613. /**
  100614. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  100615. * is automatically returned to its default position (expected to be above ground plane).
  100616. */
  100617. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  100618. var _this = this;
  100619. if (this._elevationReturnTime < 0) {
  100620. return;
  100621. }
  100622. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  100623. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  100624. var limitBeta = Math.PI * 0.5;
  100625. // Bring the camera back up if below the ground plane
  100626. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  100627. this._betaIsAnimating = true;
  100628. //Transition to new position
  100629. this.stopAllAnimations();
  100630. if (!this._betaTransition) {
  100631. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100632. }
  100633. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  100634. _this._clearAnimationLocks();
  100635. _this.stopAllAnimations();
  100636. });
  100637. if (animatabe) {
  100638. this._animatables.push(animatabe);
  100639. }
  100640. }
  100641. };
  100642. /**
  100643. * Returns the frustum slope based on the canvas ratio and camera FOV
  100644. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  100645. */
  100646. FramingBehavior.prototype._getFrustumSlope = function () {
  100647. // Calculate the viewport ratio
  100648. // Aspect Ratio is Height/Width.
  100649. var camera = this._attachedCamera;
  100650. if (!camera) {
  100651. return BABYLON.Vector2.Zero();
  100652. }
  100653. var engine = camera.getScene().getEngine();
  100654. var aspectRatio = engine.getAspectRatio(camera);
  100655. // Camera FOV is the vertical field of view (top-bottom) in radians.
  100656. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  100657. var frustumSlopeY = Math.tan(camera.fov / 2);
  100658. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  100659. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  100660. // along the forward vector.
  100661. var frustumSlopeX = frustumSlopeY * aspectRatio;
  100662. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  100663. };
  100664. /**
  100665. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  100666. */
  100667. FramingBehavior.prototype._clearAnimationLocks = function () {
  100668. this._betaIsAnimating = false;
  100669. };
  100670. /**
  100671. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100672. */
  100673. FramingBehavior.prototype._applyUserInteraction = function () {
  100674. if (this.isUserIsMoving) {
  100675. this._lastInteractionTime = BABYLON.Tools.Now;
  100676. this.stopAllAnimations();
  100677. this._clearAnimationLocks();
  100678. }
  100679. };
  100680. /**
  100681. * Stops and removes all animations that have been applied to the camera
  100682. */
  100683. FramingBehavior.prototype.stopAllAnimations = function () {
  100684. if (this._attachedCamera) {
  100685. this._attachedCamera.animations = [];
  100686. }
  100687. while (this._animatables.length) {
  100688. if (this._animatables[0]) {
  100689. this._animatables[0].onAnimationEnd = null;
  100690. this._animatables[0].stop();
  100691. }
  100692. this._animatables.shift();
  100693. }
  100694. };
  100695. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  100696. /**
  100697. * Gets a value indicating if the user is moving the camera
  100698. */
  100699. get: function () {
  100700. if (!this._attachedCamera) {
  100701. return false;
  100702. }
  100703. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100704. this._attachedCamera.inertialBetaOffset !== 0 ||
  100705. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100706. this._attachedCamera.inertialPanningX !== 0 ||
  100707. this._attachedCamera.inertialPanningY !== 0 ||
  100708. this._isPointerDown;
  100709. },
  100710. enumerable: true,
  100711. configurable: true
  100712. });
  100713. /**
  100714. * The easing function used by animations
  100715. */
  100716. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  100717. /**
  100718. * The easing mode used by animations
  100719. */
  100720. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  100721. // Statics
  100722. /**
  100723. * The camera can move all the way towards the mesh.
  100724. */
  100725. FramingBehavior.IgnoreBoundsSizeMode = 0;
  100726. /**
  100727. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  100728. */
  100729. FramingBehavior.FitFrustumSidesMode = 1;
  100730. return FramingBehavior;
  100731. }());
  100732. BABYLON.FramingBehavior = FramingBehavior;
  100733. })(BABYLON || (BABYLON = {}));
  100734. //# sourceMappingURL=babylon.framingBehavior.js.map
  100735. var BABYLON;
  100736. (function (BABYLON) {
  100737. /**
  100738. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  100739. */
  100740. var BouncingBehavior = /** @class */ (function () {
  100741. function BouncingBehavior() {
  100742. /**
  100743. * The duration of the animation, in milliseconds
  100744. */
  100745. this.transitionDuration = 450;
  100746. /**
  100747. * Length of the distance animated by the transition when lower radius is reached
  100748. */
  100749. this.lowerRadiusTransitionRange = 2;
  100750. /**
  100751. * Length of the distance animated by the transition when upper radius is reached
  100752. */
  100753. this.upperRadiusTransitionRange = -2;
  100754. this._autoTransitionRange = false;
  100755. // Animations
  100756. this._radiusIsAnimating = false;
  100757. this._radiusBounceTransition = null;
  100758. this._animatables = new Array();
  100759. }
  100760. Object.defineProperty(BouncingBehavior.prototype, "name", {
  100761. get: function () {
  100762. return "Bouncing";
  100763. },
  100764. enumerable: true,
  100765. configurable: true
  100766. });
  100767. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  100768. /**
  100769. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100770. */
  100771. get: function () {
  100772. return this._autoTransitionRange;
  100773. },
  100774. /**
  100775. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100776. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  100777. */
  100778. set: function (value) {
  100779. var _this = this;
  100780. if (this._autoTransitionRange === value) {
  100781. return;
  100782. }
  100783. this._autoTransitionRange = value;
  100784. var camera = this._attachedCamera;
  100785. if (!camera) {
  100786. return;
  100787. }
  100788. if (value) {
  100789. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100790. if (!mesh) {
  100791. return;
  100792. }
  100793. mesh.computeWorldMatrix(true);
  100794. var diagonal = mesh.getBoundingInfo().diagonalLength;
  100795. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  100796. _this.upperRadiusTransitionRange = diagonal * 0.05;
  100797. });
  100798. }
  100799. else if (this._onMeshTargetChangedObserver) {
  100800. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100801. }
  100802. },
  100803. enumerable: true,
  100804. configurable: true
  100805. });
  100806. BouncingBehavior.prototype.init = function () {
  100807. // Do notihng
  100808. };
  100809. BouncingBehavior.prototype.attach = function (camera) {
  100810. var _this = this;
  100811. this._attachedCamera = camera;
  100812. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100813. if (!_this._attachedCamera) {
  100814. return;
  100815. }
  100816. // Add the bounce animation to the lower radius limit
  100817. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  100818. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  100819. }
  100820. // Add the bounce animation to the upper radius limit
  100821. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  100822. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  100823. }
  100824. });
  100825. };
  100826. BouncingBehavior.prototype.detach = function () {
  100827. if (!this._attachedCamera) {
  100828. return;
  100829. }
  100830. if (this._onAfterCheckInputsObserver) {
  100831. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100832. }
  100833. if (this._onMeshTargetChangedObserver) {
  100834. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100835. }
  100836. this._attachedCamera = null;
  100837. };
  100838. /**
  100839. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  100840. * @param radiusLimit The limit to check against.
  100841. * @return Bool to indicate if at limit.
  100842. */
  100843. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  100844. if (!this._attachedCamera) {
  100845. return false;
  100846. }
  100847. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  100848. return true;
  100849. }
  100850. return false;
  100851. };
  100852. /**
  100853. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  100854. * @param radiusDelta The delta by which to animate to. Can be negative.
  100855. */
  100856. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  100857. var _this = this;
  100858. if (!this._attachedCamera) {
  100859. return;
  100860. }
  100861. if (!this._radiusBounceTransition) {
  100862. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  100863. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  100864. }
  100865. // Prevent zoom until bounce has completed
  100866. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  100867. this._attachedCamera.wheelPrecision = Infinity;
  100868. this._attachedCamera.inertialRadiusOffset = 0;
  100869. // Animate to the radius limit
  100870. this.stopAllAnimations();
  100871. this._radiusIsAnimating = true;
  100872. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  100873. if (animatable) {
  100874. this._animatables.push(animatable);
  100875. }
  100876. };
  100877. /**
  100878. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  100879. */
  100880. BouncingBehavior.prototype._clearAnimationLocks = function () {
  100881. this._radiusIsAnimating = false;
  100882. if (this._attachedCamera) {
  100883. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  100884. }
  100885. };
  100886. /**
  100887. * Stops and removes all animations that have been applied to the camera
  100888. */
  100889. BouncingBehavior.prototype.stopAllAnimations = function () {
  100890. if (this._attachedCamera) {
  100891. this._attachedCamera.animations = [];
  100892. }
  100893. while (this._animatables.length) {
  100894. this._animatables[0].onAnimationEnd = null;
  100895. this._animatables[0].stop();
  100896. this._animatables.shift();
  100897. }
  100898. };
  100899. /**
  100900. * The easing function used by animations
  100901. */
  100902. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  100903. /**
  100904. * The easing mode used by animations
  100905. */
  100906. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  100907. return BouncingBehavior;
  100908. }());
  100909. BABYLON.BouncingBehavior = BouncingBehavior;
  100910. })(BABYLON || (BABYLON = {}));
  100911. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  100912. var BABYLON;
  100913. (function (BABYLON) {
  100914. var AutoRotationBehavior = /** @class */ (function () {
  100915. function AutoRotationBehavior() {
  100916. this._zoomStopsAnimation = false;
  100917. this._idleRotationSpeed = 0.05;
  100918. this._idleRotationWaitTime = 2000;
  100919. this._idleRotationSpinupTime = 2000;
  100920. this._isPointerDown = false;
  100921. this._lastFrameTime = null;
  100922. this._lastInteractionTime = -Infinity;
  100923. this._cameraRotationSpeed = 0;
  100924. this._lastFrameRadius = 0;
  100925. }
  100926. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  100927. get: function () {
  100928. return "AutoRotation";
  100929. },
  100930. enumerable: true,
  100931. configurable: true
  100932. });
  100933. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  100934. /**
  100935. * Gets the flag that indicates if user zooming should stop animation.
  100936. */
  100937. get: function () {
  100938. return this._zoomStopsAnimation;
  100939. },
  100940. /**
  100941. * Sets the flag that indicates if user zooming should stop animation.
  100942. */
  100943. set: function (flag) {
  100944. this._zoomStopsAnimation = flag;
  100945. },
  100946. enumerable: true,
  100947. configurable: true
  100948. });
  100949. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  100950. /**
  100951. * Gets the default speed at which the camera rotates around the model.
  100952. */
  100953. get: function () {
  100954. return this._idleRotationSpeed;
  100955. },
  100956. /**
  100957. * Sets the default speed at which the camera rotates around the model.
  100958. */
  100959. set: function (speed) {
  100960. this._idleRotationSpeed = speed;
  100961. },
  100962. enumerable: true,
  100963. configurable: true
  100964. });
  100965. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  100966. /**
  100967. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  100968. */
  100969. get: function () {
  100970. return this._idleRotationWaitTime;
  100971. },
  100972. /**
  100973. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  100974. */
  100975. set: function (time) {
  100976. this._idleRotationWaitTime = time;
  100977. },
  100978. enumerable: true,
  100979. configurable: true
  100980. });
  100981. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  100982. /**
  100983. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100984. */
  100985. get: function () {
  100986. return this._idleRotationSpinupTime;
  100987. },
  100988. /**
  100989. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100990. */
  100991. set: function (time) {
  100992. this._idleRotationSpinupTime = time;
  100993. },
  100994. enumerable: true,
  100995. configurable: true
  100996. });
  100997. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  100998. /**
  100999. * Gets a value indicating if the camera is currently rotating because of this behavior
  101000. */
  101001. get: function () {
  101002. return Math.abs(this._cameraRotationSpeed) > 0;
  101003. },
  101004. enumerable: true,
  101005. configurable: true
  101006. });
  101007. AutoRotationBehavior.prototype.init = function () {
  101008. // Do notihng
  101009. };
  101010. AutoRotationBehavior.prototype.attach = function (camera) {
  101011. var _this = this;
  101012. this._attachedCamera = camera;
  101013. var scene = this._attachedCamera.getScene();
  101014. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  101015. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  101016. _this._isPointerDown = true;
  101017. return;
  101018. }
  101019. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  101020. _this._isPointerDown = false;
  101021. }
  101022. });
  101023. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101024. var now = BABYLON.Tools.Now;
  101025. var dt = 0;
  101026. if (_this._lastFrameTime != null) {
  101027. dt = now - _this._lastFrameTime;
  101028. }
  101029. _this._lastFrameTime = now;
  101030. // Stop the animation if there is user interaction and the animation should stop for this interaction
  101031. _this._applyUserInteraction();
  101032. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  101033. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  101034. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  101035. // Step camera rotation by rotation speed
  101036. if (_this._attachedCamera) {
  101037. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  101038. }
  101039. });
  101040. };
  101041. AutoRotationBehavior.prototype.detach = function () {
  101042. if (!this._attachedCamera) {
  101043. return;
  101044. }
  101045. var scene = this._attachedCamera.getScene();
  101046. if (this._onPrePointerObservableObserver) {
  101047. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  101048. }
  101049. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101050. this._attachedCamera = null;
  101051. };
  101052. /**
  101053. * Returns true if user is scrolling.
  101054. * @return true if user is scrolling.
  101055. */
  101056. AutoRotationBehavior.prototype._userIsZooming = function () {
  101057. if (!this._attachedCamera) {
  101058. return false;
  101059. }
  101060. return this._attachedCamera.inertialRadiusOffset !== 0;
  101061. };
  101062. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  101063. if (!this._attachedCamera) {
  101064. return false;
  101065. }
  101066. var zoomHasHitLimit = false;
  101067. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  101068. zoomHasHitLimit = true;
  101069. }
  101070. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  101071. this._lastFrameRadius = this._attachedCamera.radius;
  101072. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  101073. };
  101074. /**
  101075. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  101076. */
  101077. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  101078. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  101079. this._lastInteractionTime = BABYLON.Tools.Now;
  101080. }
  101081. };
  101082. // Tools
  101083. AutoRotationBehavior.prototype._userIsMoving = function () {
  101084. if (!this._attachedCamera) {
  101085. return false;
  101086. }
  101087. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  101088. this._attachedCamera.inertialBetaOffset !== 0 ||
  101089. this._attachedCamera.inertialRadiusOffset !== 0 ||
  101090. this._attachedCamera.inertialPanningX !== 0 ||
  101091. this._attachedCamera.inertialPanningY !== 0 ||
  101092. this._isPointerDown;
  101093. };
  101094. return AutoRotationBehavior;
  101095. }());
  101096. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  101097. })(BABYLON || (BABYLON = {}));
  101098. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  101099. var BABYLON;
  101100. (function (BABYLON) {
  101101. var NullEngineOptions = /** @class */ (function () {
  101102. function NullEngineOptions() {
  101103. this.renderWidth = 512;
  101104. this.renderHeight = 256;
  101105. this.textureSize = 512;
  101106. this.deterministicLockstep = false;
  101107. this.lockstepMaxSteps = 4;
  101108. }
  101109. return NullEngineOptions;
  101110. }());
  101111. BABYLON.NullEngineOptions = NullEngineOptions;
  101112. /**
  101113. * The null engine class provides support for headless version of babylon.js.
  101114. * This can be used in server side scenario or for testing purposes
  101115. */
  101116. var NullEngine = /** @class */ (function (_super) {
  101117. __extends(NullEngine, _super);
  101118. function NullEngine(options) {
  101119. if (options === void 0) { options = new NullEngineOptions(); }
  101120. var _this = _super.call(this, null) || this;
  101121. if (options.deterministicLockstep === undefined) {
  101122. options.deterministicLockstep = false;
  101123. }
  101124. if (options.lockstepMaxSteps === undefined) {
  101125. options.lockstepMaxSteps = 4;
  101126. }
  101127. _this._options = options;
  101128. // Init caps
  101129. // We consider we are on a webgl1 capable device
  101130. _this._caps = new BABYLON.EngineCapabilities();
  101131. _this._caps.maxTexturesImageUnits = 16;
  101132. _this._caps.maxVertexTextureImageUnits = 16;
  101133. _this._caps.maxTextureSize = 512;
  101134. _this._caps.maxCubemapTextureSize = 512;
  101135. _this._caps.maxRenderTextureSize = 512;
  101136. _this._caps.maxVertexAttribs = 16;
  101137. _this._caps.maxVaryingVectors = 16;
  101138. _this._caps.maxFragmentUniformVectors = 16;
  101139. _this._caps.maxVertexUniformVectors = 16;
  101140. // Extensions
  101141. _this._caps.standardDerivatives = false;
  101142. _this._caps.astc = null;
  101143. _this._caps.s3tc = null;
  101144. _this._caps.pvrtc = null;
  101145. _this._caps.etc1 = null;
  101146. _this._caps.etc2 = null;
  101147. _this._caps.textureAnisotropicFilterExtension = null;
  101148. _this._caps.maxAnisotropy = 0;
  101149. _this._caps.uintIndices = false;
  101150. _this._caps.fragmentDepthSupported = false;
  101151. _this._caps.highPrecisionShaderSupported = true;
  101152. _this._caps.colorBufferFloat = false;
  101153. _this._caps.textureFloat = false;
  101154. _this._caps.textureFloatLinearFiltering = false;
  101155. _this._caps.textureFloatRender = false;
  101156. _this._caps.textureHalfFloat = false;
  101157. _this._caps.textureHalfFloatLinearFiltering = false;
  101158. _this._caps.textureHalfFloatRender = false;
  101159. _this._caps.textureLOD = false;
  101160. _this._caps.drawBuffersExtension = false;
  101161. _this._caps.depthTextureExtension = false;
  101162. _this._caps.vertexArrayObject = false;
  101163. _this._caps.instancedArrays = false;
  101164. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  101165. // Wrappers
  101166. if (typeof URL === "undefined") {
  101167. URL = {
  101168. createObjectURL: function () { },
  101169. revokeObjectURL: function () { }
  101170. };
  101171. }
  101172. if (typeof Blob === "undefined") {
  101173. Blob = function () { };
  101174. }
  101175. return _this;
  101176. }
  101177. NullEngine.prototype.isDeterministicLockStep = function () {
  101178. return this._options.deterministicLockstep;
  101179. };
  101180. NullEngine.prototype.getLockstepMaxSteps = function () {
  101181. return this._options.lockstepMaxSteps;
  101182. };
  101183. NullEngine.prototype.getHardwareScalingLevel = function () {
  101184. return 1.0;
  101185. };
  101186. NullEngine.prototype.createVertexBuffer = function (vertices) {
  101187. return {
  101188. capacity: 0,
  101189. references: 1,
  101190. is32Bits: false
  101191. };
  101192. };
  101193. NullEngine.prototype.createIndexBuffer = function (indices) {
  101194. return {
  101195. capacity: 0,
  101196. references: 1,
  101197. is32Bits: false
  101198. };
  101199. };
  101200. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  101201. if (stencil === void 0) { stencil = false; }
  101202. };
  101203. NullEngine.prototype.getRenderWidth = function (useScreen) {
  101204. if (useScreen === void 0) { useScreen = false; }
  101205. if (!useScreen && this._currentRenderTarget) {
  101206. return this._currentRenderTarget.width;
  101207. }
  101208. return this._options.renderWidth;
  101209. };
  101210. NullEngine.prototype.getRenderHeight = function (useScreen) {
  101211. if (useScreen === void 0) { useScreen = false; }
  101212. if (!useScreen && this._currentRenderTarget) {
  101213. return this._currentRenderTarget.height;
  101214. }
  101215. return this._options.renderHeight;
  101216. };
  101217. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  101218. this._cachedViewport = viewport;
  101219. };
  101220. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  101221. return {
  101222. transformFeedback: null,
  101223. __SPECTOR_rebuildProgram: null
  101224. };
  101225. };
  101226. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  101227. return [];
  101228. };
  101229. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  101230. return [];
  101231. };
  101232. NullEngine.prototype.bindSamplers = function (effect) {
  101233. this._currentEffect = null;
  101234. };
  101235. NullEngine.prototype.enableEffect = function (effect) {
  101236. this._currentEffect = effect;
  101237. if (effect.onBind) {
  101238. effect.onBind(effect);
  101239. }
  101240. effect.onBindObservable.notifyObservers(effect);
  101241. };
  101242. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  101243. if (zOffset === void 0) { zOffset = 0; }
  101244. if (reverseSide === void 0) { reverseSide = false; }
  101245. };
  101246. NullEngine.prototype.setIntArray = function (uniform, array) {
  101247. };
  101248. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  101249. };
  101250. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  101251. };
  101252. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  101253. };
  101254. NullEngine.prototype.setFloatArray = function (uniform, array) {
  101255. };
  101256. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  101257. };
  101258. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  101259. };
  101260. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  101261. };
  101262. NullEngine.prototype.setArray = function (uniform, array) {
  101263. };
  101264. NullEngine.prototype.setArray2 = function (uniform, array) {
  101265. };
  101266. NullEngine.prototype.setArray3 = function (uniform, array) {
  101267. };
  101268. NullEngine.prototype.setArray4 = function (uniform, array) {
  101269. };
  101270. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  101271. };
  101272. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  101273. };
  101274. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  101275. };
  101276. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  101277. };
  101278. NullEngine.prototype.setFloat = function (uniform, value) {
  101279. };
  101280. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  101281. };
  101282. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  101283. };
  101284. NullEngine.prototype.setBool = function (uniform, bool) {
  101285. };
  101286. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  101287. };
  101288. NullEngine.prototype.setColor3 = function (uniform, color3) {
  101289. };
  101290. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  101291. };
  101292. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  101293. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  101294. if (this._alphaMode === mode) {
  101295. return;
  101296. }
  101297. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  101298. if (!noDepthWriteChange) {
  101299. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  101300. }
  101301. this._alphaMode = mode;
  101302. };
  101303. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  101304. };
  101305. NullEngine.prototype.wipeCaches = function (bruteForce) {
  101306. if (this.preventCacheWipeBetweenFrames) {
  101307. return;
  101308. }
  101309. this.resetTextureCache();
  101310. this._currentEffect = null;
  101311. if (bruteForce) {
  101312. this._currentProgram = null;
  101313. this._stencilState.reset();
  101314. this._depthCullingState.reset();
  101315. this._alphaState.reset();
  101316. }
  101317. this._cachedVertexBuffers = null;
  101318. this._cachedIndexBuffer = null;
  101319. this._cachedEffectForVertexBuffers = null;
  101320. };
  101321. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  101322. };
  101323. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  101324. };
  101325. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  101326. };
  101327. NullEngine.prototype._createTexture = function () {
  101328. return {};
  101329. };
  101330. NullEngine.prototype._releaseTexture = function (texture) {
  101331. };
  101332. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  101333. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101334. if (onLoad === void 0) { onLoad = null; }
  101335. if (onError === void 0) { onError = null; }
  101336. if (buffer === void 0) { buffer = null; }
  101337. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  101338. var url = String(urlArg);
  101339. texture.url = url;
  101340. texture.generateMipMaps = !noMipmap;
  101341. texture.samplingMode = samplingMode;
  101342. texture.invertY = invertY;
  101343. texture.baseWidth = this._options.textureSize;
  101344. texture.baseHeight = this._options.textureSize;
  101345. texture.width = this._options.textureSize;
  101346. texture.height = this._options.textureSize;
  101347. if (format) {
  101348. texture.format = format;
  101349. }
  101350. texture.isReady = true;
  101351. if (onLoad) {
  101352. onLoad();
  101353. }
  101354. this._internalTexturesCache.push(texture);
  101355. return texture;
  101356. };
  101357. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  101358. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  101359. if (options !== undefined && typeof options === "object") {
  101360. fullOptions.generateMipMaps = options.generateMipMaps;
  101361. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  101362. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  101363. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  101364. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  101365. }
  101366. else {
  101367. fullOptions.generateMipMaps = options;
  101368. fullOptions.generateDepthBuffer = true;
  101369. fullOptions.generateStencilBuffer = false;
  101370. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101371. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  101372. }
  101373. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  101374. var width = size.width || size;
  101375. var height = size.height || size;
  101376. texture._depthStencilBuffer = {};
  101377. texture._framebuffer = {};
  101378. texture.baseWidth = width;
  101379. texture.baseHeight = height;
  101380. texture.width = width;
  101381. texture.height = height;
  101382. texture.isReady = true;
  101383. texture.samples = 1;
  101384. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  101385. texture.samplingMode = fullOptions.samplingMode;
  101386. texture.type = fullOptions.type;
  101387. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  101388. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  101389. this._internalTexturesCache.push(texture);
  101390. return texture;
  101391. };
  101392. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  101393. texture.samplingMode = samplingMode;
  101394. };
  101395. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  101396. if (this._currentRenderTarget) {
  101397. this.unBindFramebuffer(this._currentRenderTarget);
  101398. }
  101399. this._currentRenderTarget = texture;
  101400. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  101401. if (this._cachedViewport && !forceFullscreenViewport) {
  101402. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  101403. }
  101404. };
  101405. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  101406. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  101407. this._currentRenderTarget = null;
  101408. if (onBeforeUnbind) {
  101409. if (texture._MSAAFramebuffer) {
  101410. this._currentFramebuffer = texture._framebuffer;
  101411. }
  101412. onBeforeUnbind();
  101413. }
  101414. this._currentFramebuffer = null;
  101415. };
  101416. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  101417. var vbo = {
  101418. capacity: 1,
  101419. references: 1,
  101420. is32Bits: false
  101421. };
  101422. return vbo;
  101423. };
  101424. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  101425. if (premulAlpha === void 0) { premulAlpha = false; }
  101426. };
  101427. /**
  101428. * Get the current error code of the webGL context
  101429. * @returns the error code
  101430. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  101431. */
  101432. NullEngine.prototype.getError = function () {
  101433. return 0;
  101434. };
  101435. /** @hidden */
  101436. NullEngine.prototype._getUnpackAlignement = function () {
  101437. return 1;
  101438. };
  101439. /** @hidden */
  101440. NullEngine.prototype._unpackFlipY = function (value) {
  101441. };
  101442. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  101443. if (offset === void 0) { offset = 0; }
  101444. };
  101445. /**
  101446. * Updates a dynamic vertex buffer.
  101447. * @param vertexBuffer the vertex buffer to update
  101448. * @param data the data used to update the vertex buffer
  101449. * @param byteOffset the byte offset of the data (optional)
  101450. * @param byteLength the byte length of the data (optional)
  101451. */
  101452. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  101453. };
  101454. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  101455. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  101456. this._boundTexturesCache[this._activeChannel] = texture;
  101457. return true;
  101458. }
  101459. return false;
  101460. };
  101461. NullEngine.prototype._bindTexture = function (channel, texture) {
  101462. if (channel < 0) {
  101463. return;
  101464. }
  101465. this._bindTextureDirectly(0, texture);
  101466. };
  101467. NullEngine.prototype._releaseBuffer = function (buffer) {
  101468. buffer.references--;
  101469. if (buffer.references === 0) {
  101470. return true;
  101471. }
  101472. return false;
  101473. };
  101474. NullEngine.prototype.releaseEffects = function () {
  101475. };
  101476. NullEngine.prototype.displayLoadingUI = function () {
  101477. };
  101478. NullEngine.prototype.hideLoadingUI = function () {
  101479. };
  101480. /** @hidden */
  101481. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  101482. if (faceIndex === void 0) { faceIndex = 0; }
  101483. if (lod === void 0) { lod = 0; }
  101484. };
  101485. /** @hidden */
  101486. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  101487. if (faceIndex === void 0) { faceIndex = 0; }
  101488. if (lod === void 0) { lod = 0; }
  101489. };
  101490. /** @hidden */
  101491. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  101492. if (faceIndex === void 0) { faceIndex = 0; }
  101493. if (lod === void 0) { lod = 0; }
  101494. };
  101495. /** @hidden */
  101496. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  101497. if (faceIndex === void 0) { faceIndex = 0; }
  101498. if (lod === void 0) { lod = 0; }
  101499. };
  101500. return NullEngine;
  101501. }(BABYLON.Engine));
  101502. BABYLON.NullEngine = NullEngine;
  101503. })(BABYLON || (BABYLON = {}));
  101504. //# sourceMappingURL=babylon.nullEngine.js.map
  101505. var BABYLON;
  101506. (function (BABYLON) {
  101507. /**
  101508. * This class can be used to get instrumentation data from a Babylon engine
  101509. */
  101510. var EngineInstrumentation = /** @class */ (function () {
  101511. function EngineInstrumentation(engine) {
  101512. this.engine = engine;
  101513. this._captureGPUFrameTime = false;
  101514. this._gpuFrameTime = new BABYLON.PerfCounter();
  101515. this._captureShaderCompilationTime = false;
  101516. this._shaderCompilationTime = new BABYLON.PerfCounter();
  101517. // Observers
  101518. this._onBeginFrameObserver = null;
  101519. this._onEndFrameObserver = null;
  101520. this._onBeforeShaderCompilationObserver = null;
  101521. this._onAfterShaderCompilationObserver = null;
  101522. }
  101523. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  101524. // Properties
  101525. /**
  101526. * Gets the perf counter used for GPU frame time
  101527. */
  101528. get: function () {
  101529. return this._gpuFrameTime;
  101530. },
  101531. enumerable: true,
  101532. configurable: true
  101533. });
  101534. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  101535. /**
  101536. * Gets the GPU frame time capture status
  101537. */
  101538. get: function () {
  101539. return this._captureGPUFrameTime;
  101540. },
  101541. /**
  101542. * Enable or disable the GPU frame time capture
  101543. */
  101544. set: function (value) {
  101545. var _this = this;
  101546. if (value === this._captureGPUFrameTime) {
  101547. return;
  101548. }
  101549. this._captureGPUFrameTime = value;
  101550. if (value) {
  101551. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  101552. if (!_this._gpuFrameTimeToken) {
  101553. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  101554. }
  101555. });
  101556. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  101557. if (!_this._gpuFrameTimeToken) {
  101558. return;
  101559. }
  101560. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  101561. if (time > -1) {
  101562. _this._gpuFrameTimeToken = null;
  101563. _this._gpuFrameTime.fetchNewFrame();
  101564. _this._gpuFrameTime.addCount(time, true);
  101565. }
  101566. });
  101567. }
  101568. else {
  101569. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101570. this._onBeginFrameObserver = null;
  101571. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101572. this._onEndFrameObserver = null;
  101573. }
  101574. },
  101575. enumerable: true,
  101576. configurable: true
  101577. });
  101578. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  101579. /**
  101580. * Gets the perf counter used for shader compilation time
  101581. */
  101582. get: function () {
  101583. return this._shaderCompilationTime;
  101584. },
  101585. enumerable: true,
  101586. configurable: true
  101587. });
  101588. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  101589. /**
  101590. * Gets the shader compilation time capture status
  101591. */
  101592. get: function () {
  101593. return this._captureShaderCompilationTime;
  101594. },
  101595. /**
  101596. * Enable or disable the shader compilation time capture
  101597. */
  101598. set: function (value) {
  101599. var _this = this;
  101600. if (value === this._captureShaderCompilationTime) {
  101601. return;
  101602. }
  101603. this._captureShaderCompilationTime = value;
  101604. if (value) {
  101605. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  101606. _this._shaderCompilationTime.fetchNewFrame();
  101607. _this._shaderCompilationTime.beginMonitoring();
  101608. });
  101609. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  101610. _this._shaderCompilationTime.endMonitoring();
  101611. });
  101612. }
  101613. else {
  101614. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101615. this._onBeforeShaderCompilationObserver = null;
  101616. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101617. this._onAfterShaderCompilationObserver = null;
  101618. }
  101619. },
  101620. enumerable: true,
  101621. configurable: true
  101622. });
  101623. EngineInstrumentation.prototype.dispose = function () {
  101624. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101625. this._onBeginFrameObserver = null;
  101626. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101627. this._onEndFrameObserver = null;
  101628. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101629. this._onBeforeShaderCompilationObserver = null;
  101630. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101631. this._onAfterShaderCompilationObserver = null;
  101632. this.engine = null;
  101633. };
  101634. return EngineInstrumentation;
  101635. }());
  101636. BABYLON.EngineInstrumentation = EngineInstrumentation;
  101637. })(BABYLON || (BABYLON = {}));
  101638. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  101639. var BABYLON;
  101640. (function (BABYLON) {
  101641. /**
  101642. * This class can be used to get instrumentation data from a Babylon engine
  101643. */
  101644. var SceneInstrumentation = /** @class */ (function () {
  101645. function SceneInstrumentation(scene) {
  101646. var _this = this;
  101647. this.scene = scene;
  101648. this._captureActiveMeshesEvaluationTime = false;
  101649. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  101650. this._captureRenderTargetsRenderTime = false;
  101651. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  101652. this._captureFrameTime = false;
  101653. this._frameTime = new BABYLON.PerfCounter();
  101654. this._captureRenderTime = false;
  101655. this._renderTime = new BABYLON.PerfCounter();
  101656. this._captureInterFrameTime = false;
  101657. this._interFrameTime = new BABYLON.PerfCounter();
  101658. this._captureParticlesRenderTime = false;
  101659. this._particlesRenderTime = new BABYLON.PerfCounter();
  101660. this._captureSpritesRenderTime = false;
  101661. this._spritesRenderTime = new BABYLON.PerfCounter();
  101662. this._capturePhysicsTime = false;
  101663. this._physicsTime = new BABYLON.PerfCounter();
  101664. this._captureAnimationsTime = false;
  101665. this._animationsTime = new BABYLON.PerfCounter();
  101666. this._captureCameraRenderTime = false;
  101667. this._cameraRenderTime = new BABYLON.PerfCounter();
  101668. // Observers
  101669. this._onBeforeActiveMeshesEvaluationObserver = null;
  101670. this._onAfterActiveMeshesEvaluationObserver = null;
  101671. this._onBeforeRenderTargetsRenderObserver = null;
  101672. this._onAfterRenderTargetsRenderObserver = null;
  101673. this._onAfterRenderObserver = null;
  101674. this._onBeforeDrawPhaseObserver = null;
  101675. this._onAfterDrawPhaseObserver = null;
  101676. this._onBeforeAnimationsObserver = null;
  101677. this._onBeforeParticlesRenderingObserver = null;
  101678. this._onAfterParticlesRenderingObserver = null;
  101679. this._onBeforeSpritesRenderingObserver = null;
  101680. this._onAfterSpritesRenderingObserver = null;
  101681. this._onBeforePhysicsObserver = null;
  101682. this._onAfterPhysicsObserver = null;
  101683. this._onAfterAnimationsObserver = null;
  101684. this._onBeforeCameraRenderObserver = null;
  101685. this._onAfterCameraRenderObserver = null;
  101686. // Before render
  101687. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  101688. if (_this._captureActiveMeshesEvaluationTime) {
  101689. _this._activeMeshesEvaluationTime.fetchNewFrame();
  101690. }
  101691. if (_this._captureRenderTargetsRenderTime) {
  101692. _this._renderTargetsRenderTime.fetchNewFrame();
  101693. }
  101694. if (_this._captureFrameTime) {
  101695. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  101696. _this._frameTime.beginMonitoring();
  101697. }
  101698. if (_this._captureInterFrameTime) {
  101699. _this._interFrameTime.endMonitoring();
  101700. }
  101701. if (_this._captureParticlesRenderTime) {
  101702. _this._particlesRenderTime.fetchNewFrame();
  101703. }
  101704. if (_this._captureSpritesRenderTime) {
  101705. _this._spritesRenderTime.fetchNewFrame();
  101706. }
  101707. if (_this._captureAnimationsTime) {
  101708. _this._animationsTime.beginMonitoring();
  101709. }
  101710. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  101711. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  101712. });
  101713. // After render
  101714. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  101715. if (_this._captureFrameTime) {
  101716. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  101717. _this._frameTime.endMonitoring();
  101718. }
  101719. if (_this._captureRenderTime) {
  101720. _this._renderTime.endMonitoring(false);
  101721. }
  101722. if (_this._captureInterFrameTime) {
  101723. _this._interFrameTime.beginMonitoring();
  101724. }
  101725. });
  101726. }
  101727. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  101728. // Properties
  101729. /**
  101730. * Gets the perf counter used for active meshes evaluation time
  101731. */
  101732. get: function () {
  101733. return this._activeMeshesEvaluationTime;
  101734. },
  101735. enumerable: true,
  101736. configurable: true
  101737. });
  101738. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  101739. /**
  101740. * Gets the active meshes evaluation time capture status
  101741. */
  101742. get: function () {
  101743. return this._captureActiveMeshesEvaluationTime;
  101744. },
  101745. /**
  101746. * Enable or disable the active meshes evaluation time capture
  101747. */
  101748. set: function (value) {
  101749. var _this = this;
  101750. if (value === this._captureActiveMeshesEvaluationTime) {
  101751. return;
  101752. }
  101753. this._captureActiveMeshesEvaluationTime = value;
  101754. if (value) {
  101755. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  101756. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  101757. _this._activeMeshesEvaluationTime.beginMonitoring();
  101758. });
  101759. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  101760. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  101761. _this._activeMeshesEvaluationTime.endMonitoring();
  101762. });
  101763. }
  101764. else {
  101765. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101766. this._onBeforeActiveMeshesEvaluationObserver = null;
  101767. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101768. this._onAfterActiveMeshesEvaluationObserver = null;
  101769. }
  101770. },
  101771. enumerable: true,
  101772. configurable: true
  101773. });
  101774. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  101775. /**
  101776. * Gets the perf counter used for render targets render time
  101777. */
  101778. get: function () {
  101779. return this._renderTargetsRenderTime;
  101780. },
  101781. enumerable: true,
  101782. configurable: true
  101783. });
  101784. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  101785. /**
  101786. * Gets the render targets render time capture status
  101787. */
  101788. get: function () {
  101789. return this._captureRenderTargetsRenderTime;
  101790. },
  101791. /**
  101792. * Enable or disable the render targets render time capture
  101793. */
  101794. set: function (value) {
  101795. var _this = this;
  101796. if (value === this._captureRenderTargetsRenderTime) {
  101797. return;
  101798. }
  101799. this._captureRenderTargetsRenderTime = value;
  101800. if (value) {
  101801. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  101802. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  101803. _this._renderTargetsRenderTime.beginMonitoring();
  101804. });
  101805. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  101806. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  101807. _this._renderTargetsRenderTime.endMonitoring(false);
  101808. });
  101809. }
  101810. else {
  101811. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101812. this._onBeforeRenderTargetsRenderObserver = null;
  101813. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101814. this._onAfterRenderTargetsRenderObserver = null;
  101815. }
  101816. },
  101817. enumerable: true,
  101818. configurable: true
  101819. });
  101820. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  101821. /**
  101822. * Gets the perf counter used for particles render time
  101823. */
  101824. get: function () {
  101825. return this._particlesRenderTime;
  101826. },
  101827. enumerable: true,
  101828. configurable: true
  101829. });
  101830. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  101831. /**
  101832. * Gets the particles render time capture status
  101833. */
  101834. get: function () {
  101835. return this._captureParticlesRenderTime;
  101836. },
  101837. /**
  101838. * Enable or disable the particles render time capture
  101839. */
  101840. set: function (value) {
  101841. var _this = this;
  101842. if (value === this._captureParticlesRenderTime) {
  101843. return;
  101844. }
  101845. this._captureParticlesRenderTime = value;
  101846. if (value) {
  101847. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  101848. BABYLON.Tools.StartPerformanceCounter("Particles");
  101849. _this._particlesRenderTime.beginMonitoring();
  101850. });
  101851. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  101852. BABYLON.Tools.EndPerformanceCounter("Particles");
  101853. _this._particlesRenderTime.endMonitoring(false);
  101854. });
  101855. }
  101856. else {
  101857. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101858. this._onBeforeParticlesRenderingObserver = null;
  101859. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101860. this._onAfterParticlesRenderingObserver = null;
  101861. }
  101862. },
  101863. enumerable: true,
  101864. configurable: true
  101865. });
  101866. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  101867. /**
  101868. * Gets the perf counter used for sprites render time
  101869. */
  101870. get: function () {
  101871. return this._spritesRenderTime;
  101872. },
  101873. enumerable: true,
  101874. configurable: true
  101875. });
  101876. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  101877. /**
  101878. * Gets the sprites render time capture status
  101879. */
  101880. get: function () {
  101881. return this._captureSpritesRenderTime;
  101882. },
  101883. /**
  101884. * Enable or disable the sprites render time capture
  101885. */
  101886. set: function (value) {
  101887. var _this = this;
  101888. if (value === this._captureSpritesRenderTime) {
  101889. return;
  101890. }
  101891. this._captureSpritesRenderTime = value;
  101892. if (value) {
  101893. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  101894. BABYLON.Tools.StartPerformanceCounter("Sprites");
  101895. _this._spritesRenderTime.beginMonitoring();
  101896. });
  101897. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  101898. BABYLON.Tools.EndPerformanceCounter("Sprites");
  101899. _this._spritesRenderTime.endMonitoring(false);
  101900. });
  101901. }
  101902. else {
  101903. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101904. this._onBeforeSpritesRenderingObserver = null;
  101905. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101906. this._onAfterSpritesRenderingObserver = null;
  101907. }
  101908. },
  101909. enumerable: true,
  101910. configurable: true
  101911. });
  101912. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  101913. /**
  101914. * Gets the perf counter used for physics time
  101915. */
  101916. get: function () {
  101917. return this._physicsTime;
  101918. },
  101919. enumerable: true,
  101920. configurable: true
  101921. });
  101922. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  101923. /**
  101924. * Gets the physics time capture status
  101925. */
  101926. get: function () {
  101927. return this._capturePhysicsTime;
  101928. },
  101929. /**
  101930. * Enable or disable the physics time capture
  101931. */
  101932. set: function (value) {
  101933. var _this = this;
  101934. if (value === this._capturePhysicsTime) {
  101935. return;
  101936. }
  101937. this._capturePhysicsTime = value;
  101938. if (value) {
  101939. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  101940. BABYLON.Tools.StartPerformanceCounter("Physics");
  101941. _this._physicsTime.beginMonitoring();
  101942. });
  101943. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  101944. BABYLON.Tools.EndPerformanceCounter("Physics");
  101945. _this._physicsTime.endMonitoring();
  101946. });
  101947. }
  101948. else {
  101949. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101950. this._onBeforePhysicsObserver = null;
  101951. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101952. this._onAfterPhysicsObserver = null;
  101953. }
  101954. },
  101955. enumerable: true,
  101956. configurable: true
  101957. });
  101958. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  101959. /**
  101960. * Gets the perf counter used for animations time
  101961. */
  101962. get: function () {
  101963. return this._animationsTime;
  101964. },
  101965. enumerable: true,
  101966. configurable: true
  101967. });
  101968. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  101969. /**
  101970. * Gets the animations time capture status
  101971. */
  101972. get: function () {
  101973. return this._captureAnimationsTime;
  101974. },
  101975. /**
  101976. * Enable or disable the animations time capture
  101977. */
  101978. set: function (value) {
  101979. var _this = this;
  101980. if (value === this._captureAnimationsTime) {
  101981. return;
  101982. }
  101983. this._captureAnimationsTime = value;
  101984. if (value) {
  101985. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  101986. _this._animationsTime.endMonitoring();
  101987. });
  101988. }
  101989. else {
  101990. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101991. this._onAfterAnimationsObserver = null;
  101992. }
  101993. },
  101994. enumerable: true,
  101995. configurable: true
  101996. });
  101997. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  101998. /**
  101999. * Gets the perf counter used for frame time capture
  102000. */
  102001. get: function () {
  102002. return this._frameTime;
  102003. },
  102004. enumerable: true,
  102005. configurable: true
  102006. });
  102007. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  102008. /**
  102009. * Gets the frame time capture status
  102010. */
  102011. get: function () {
  102012. return this._captureFrameTime;
  102013. },
  102014. /**
  102015. * Enable or disable the frame time capture
  102016. */
  102017. set: function (value) {
  102018. this._captureFrameTime = value;
  102019. },
  102020. enumerable: true,
  102021. configurable: true
  102022. });
  102023. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  102024. /**
  102025. * Gets the perf counter used for inter-frames time capture
  102026. */
  102027. get: function () {
  102028. return this._interFrameTime;
  102029. },
  102030. enumerable: true,
  102031. configurable: true
  102032. });
  102033. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  102034. /**
  102035. * Gets the inter-frames time capture status
  102036. */
  102037. get: function () {
  102038. return this._captureInterFrameTime;
  102039. },
  102040. /**
  102041. * Enable or disable the inter-frames time capture
  102042. */
  102043. set: function (value) {
  102044. this._captureInterFrameTime = value;
  102045. },
  102046. enumerable: true,
  102047. configurable: true
  102048. });
  102049. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  102050. /**
  102051. * Gets the perf counter used for render time capture
  102052. */
  102053. get: function () {
  102054. return this._renderTime;
  102055. },
  102056. enumerable: true,
  102057. configurable: true
  102058. });
  102059. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  102060. /**
  102061. * Gets the render time capture status
  102062. */
  102063. get: function () {
  102064. return this._captureRenderTime;
  102065. },
  102066. /**
  102067. * Enable or disable the render time capture
  102068. */
  102069. set: function (value) {
  102070. var _this = this;
  102071. if (value === this._captureRenderTime) {
  102072. return;
  102073. }
  102074. this._captureRenderTime = value;
  102075. if (value) {
  102076. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  102077. _this._renderTime.beginMonitoring();
  102078. BABYLON.Tools.StartPerformanceCounter("Main render");
  102079. });
  102080. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  102081. _this._renderTime.endMonitoring(false);
  102082. BABYLON.Tools.EndPerformanceCounter("Main render");
  102083. });
  102084. }
  102085. else {
  102086. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102087. this._onBeforeDrawPhaseObserver = null;
  102088. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102089. this._onAfterDrawPhaseObserver = null;
  102090. }
  102091. },
  102092. enumerable: true,
  102093. configurable: true
  102094. });
  102095. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  102096. /**
  102097. * Gets the perf counter used for camera render time capture
  102098. */
  102099. get: function () {
  102100. return this._cameraRenderTime;
  102101. },
  102102. enumerable: true,
  102103. configurable: true
  102104. });
  102105. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  102106. /**
  102107. * Gets the camera render time capture status
  102108. */
  102109. get: function () {
  102110. return this._captureCameraRenderTime;
  102111. },
  102112. /**
  102113. * Enable or disable the camera render time capture
  102114. */
  102115. set: function (value) {
  102116. var _this = this;
  102117. if (value === this._captureCameraRenderTime) {
  102118. return;
  102119. }
  102120. this._captureCameraRenderTime = value;
  102121. if (value) {
  102122. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  102123. _this._cameraRenderTime.beginMonitoring();
  102124. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  102125. });
  102126. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  102127. _this._cameraRenderTime.endMonitoring(false);
  102128. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  102129. });
  102130. }
  102131. else {
  102132. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102133. this._onBeforeCameraRenderObserver = null;
  102134. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102135. this._onAfterCameraRenderObserver = null;
  102136. }
  102137. },
  102138. enumerable: true,
  102139. configurable: true
  102140. });
  102141. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  102142. /**
  102143. * Gets the perf counter used for draw calls
  102144. */
  102145. get: function () {
  102146. return this.scene.getEngine()._drawCalls;
  102147. },
  102148. enumerable: true,
  102149. configurable: true
  102150. });
  102151. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  102152. /**
  102153. * Gets the perf counter used for texture collisions
  102154. */
  102155. get: function () {
  102156. return this.scene.getEngine()._textureCollisions;
  102157. },
  102158. enumerable: true,
  102159. configurable: true
  102160. });
  102161. SceneInstrumentation.prototype.dispose = function () {
  102162. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  102163. this._onAfterRenderObserver = null;
  102164. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  102165. this._onBeforeActiveMeshesEvaluationObserver = null;
  102166. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  102167. this._onAfterActiveMeshesEvaluationObserver = null;
  102168. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  102169. this._onBeforeRenderTargetsRenderObserver = null;
  102170. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  102171. this._onAfterRenderTargetsRenderObserver = null;
  102172. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  102173. this._onBeforeAnimationsObserver = null;
  102174. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  102175. this._onBeforeParticlesRenderingObserver = null;
  102176. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  102177. this._onAfterParticlesRenderingObserver = null;
  102178. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  102179. this._onBeforeSpritesRenderingObserver = null;
  102180. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  102181. this._onAfterSpritesRenderingObserver = null;
  102182. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102183. this._onBeforeDrawPhaseObserver = null;
  102184. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102185. this._onAfterDrawPhaseObserver = null;
  102186. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  102187. this._onBeforePhysicsObserver = null;
  102188. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  102189. this._onAfterPhysicsObserver = null;
  102190. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  102191. this._onAfterAnimationsObserver = null;
  102192. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102193. this._onBeforeCameraRenderObserver = null;
  102194. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102195. this._onAfterCameraRenderObserver = null;
  102196. this.scene = null;
  102197. };
  102198. return SceneInstrumentation;
  102199. }());
  102200. BABYLON.SceneInstrumentation = SceneInstrumentation;
  102201. })(BABYLON || (BABYLON = {}));
  102202. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  102203. var BABYLON;
  102204. (function (BABYLON) {
  102205. /**
  102206. * @hidden
  102207. **/
  102208. var _TimeToken = /** @class */ (function () {
  102209. function _TimeToken() {
  102210. this._timeElapsedQueryEnded = false;
  102211. }
  102212. return _TimeToken;
  102213. }());
  102214. BABYLON._TimeToken = _TimeToken;
  102215. })(BABYLON || (BABYLON = {}));
  102216. //# sourceMappingURL=babylon.timeToken.js.map
  102217. var BABYLON;
  102218. (function (BABYLON) {
  102219. /**
  102220. * Background material defines definition.
  102221. * @hidden Mainly internal Use
  102222. */
  102223. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  102224. __extends(BackgroundMaterialDefines, _super);
  102225. /**
  102226. * Constructor of the defines.
  102227. */
  102228. function BackgroundMaterialDefines() {
  102229. var _this = _super.call(this) || this;
  102230. /**
  102231. * True if the diffuse texture is in use.
  102232. */
  102233. _this.DIFFUSE = false;
  102234. /**
  102235. * The direct UV channel to use.
  102236. */
  102237. _this.DIFFUSEDIRECTUV = 0;
  102238. /**
  102239. * True if the diffuse texture is in gamma space.
  102240. */
  102241. _this.GAMMADIFFUSE = false;
  102242. /**
  102243. * True if the diffuse texture has opacity in the alpha channel.
  102244. */
  102245. _this.DIFFUSEHASALPHA = false;
  102246. /**
  102247. * True if you want the material to fade to transparent at grazing angle.
  102248. */
  102249. _this.OPACITYFRESNEL = false;
  102250. /**
  102251. * True if an extra blur needs to be added in the reflection.
  102252. */
  102253. _this.REFLECTIONBLUR = false;
  102254. /**
  102255. * True if you want the material to fade to reflection at grazing angle.
  102256. */
  102257. _this.REFLECTIONFRESNEL = false;
  102258. /**
  102259. * True if you want the material to falloff as far as you move away from the scene center.
  102260. */
  102261. _this.REFLECTIONFALLOFF = false;
  102262. /**
  102263. * False if the current Webgl implementation does not support the texture lod extension.
  102264. */
  102265. _this.TEXTURELODSUPPORT = false;
  102266. /**
  102267. * True to ensure the data are premultiplied.
  102268. */
  102269. _this.PREMULTIPLYALPHA = false;
  102270. /**
  102271. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  102272. */
  102273. _this.USERGBCOLOR = false;
  102274. /**
  102275. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  102276. * stays aligned with the desired configuration.
  102277. */
  102278. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  102279. /**
  102280. * True to add noise in order to reduce the banding effect.
  102281. */
  102282. _this.NOISE = false;
  102283. /**
  102284. * is the reflection texture in BGR color scheme?
  102285. * Mainly used to solve a bug in ios10 video tag
  102286. */
  102287. _this.REFLECTIONBGR = false;
  102288. _this.IMAGEPROCESSING = false;
  102289. _this.VIGNETTE = false;
  102290. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  102291. _this.VIGNETTEBLENDMODEOPAQUE = false;
  102292. _this.TONEMAPPING = false;
  102293. _this.CONTRAST = false;
  102294. _this.COLORCURVES = false;
  102295. _this.COLORGRADING = false;
  102296. _this.COLORGRADING3D = false;
  102297. _this.SAMPLER3DGREENDEPTH = false;
  102298. _this.SAMPLER3DBGRMAP = false;
  102299. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  102300. _this.EXPOSURE = false;
  102301. // Reflection.
  102302. _this.REFLECTION = false;
  102303. _this.REFLECTIONMAP_3D = false;
  102304. _this.REFLECTIONMAP_SPHERICAL = false;
  102305. _this.REFLECTIONMAP_PLANAR = false;
  102306. _this.REFLECTIONMAP_CUBIC = false;
  102307. _this.REFLECTIONMAP_PROJECTION = false;
  102308. _this.REFLECTIONMAP_SKYBOX = false;
  102309. _this.REFLECTIONMAP_EXPLICIT = false;
  102310. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102311. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102312. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102313. _this.INVERTCUBICMAP = false;
  102314. _this.REFLECTIONMAP_OPPOSITEZ = false;
  102315. _this.LODINREFLECTIONALPHA = false;
  102316. _this.GAMMAREFLECTION = false;
  102317. _this.RGBDREFLECTION = false;
  102318. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  102319. // Default BJS.
  102320. _this.MAINUV1 = false;
  102321. _this.MAINUV2 = false;
  102322. _this.UV1 = false;
  102323. _this.UV2 = false;
  102324. _this.CLIPPLANE = false;
  102325. _this.POINTSIZE = false;
  102326. _this.FOG = false;
  102327. _this.NORMAL = false;
  102328. _this.NUM_BONE_INFLUENCERS = 0;
  102329. _this.BonesPerMesh = 0;
  102330. _this.INSTANCES = false;
  102331. _this.SHADOWFLOAT = false;
  102332. _this.rebuild();
  102333. return _this;
  102334. }
  102335. return BackgroundMaterialDefines;
  102336. }(BABYLON.MaterialDefines));
  102337. /**
  102338. * Background material used to create an efficient environement around your scene.
  102339. */
  102340. var BackgroundMaterial = /** @class */ (function (_super) {
  102341. __extends(BackgroundMaterial, _super);
  102342. /**
  102343. * Instantiates a Background Material in the given scene
  102344. * @param name The friendly name of the material
  102345. * @param scene The scene to add the material to
  102346. */
  102347. function BackgroundMaterial(name, scene) {
  102348. var _this = _super.call(this, name, scene) || this;
  102349. /**
  102350. * Key light Color (multiply against the environement texture)
  102351. */
  102352. _this.primaryColor = BABYLON.Color3.White();
  102353. _this._primaryColorShadowLevel = 0;
  102354. _this._primaryColorHighlightLevel = 0;
  102355. /**
  102356. * Reflection Texture used in the material.
  102357. * Should be author in a specific way for the best result (refer to the documentation).
  102358. */
  102359. _this.reflectionTexture = null;
  102360. /**
  102361. * Reflection Texture level of blur.
  102362. *
  102363. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  102364. * texture twice.
  102365. */
  102366. _this.reflectionBlur = 0;
  102367. /**
  102368. * Diffuse Texture used in the material.
  102369. * Should be author in a specific way for the best result (refer to the documentation).
  102370. */
  102371. _this.diffuseTexture = null;
  102372. _this._shadowLights = null;
  102373. /**
  102374. * Specify the list of lights casting shadow on the material.
  102375. * All scene shadow lights will be included if null.
  102376. */
  102377. _this.shadowLights = null;
  102378. /**
  102379. * Helps adjusting the shadow to a softer level if required.
  102380. * 0 means black shadows and 1 means no shadows.
  102381. */
  102382. _this.shadowLevel = 0;
  102383. /**
  102384. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  102385. * It is usually zero but might be interesting to modify according to your setup.
  102386. */
  102387. _this.sceneCenter = BABYLON.Vector3.Zero();
  102388. /**
  102389. * This helps specifying that the material is falling off to the sky box at grazing angle.
  102390. * This helps ensuring a nice transition when the camera goes under the ground.
  102391. */
  102392. _this.opacityFresnel = true;
  102393. /**
  102394. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  102395. * This helps adding a mirror texture on the ground.
  102396. */
  102397. _this.reflectionFresnel = false;
  102398. /**
  102399. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  102400. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  102401. */
  102402. _this.reflectionFalloffDistance = 0.0;
  102403. /**
  102404. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  102405. */
  102406. _this.reflectionAmount = 1.0;
  102407. /**
  102408. * This specifies the weight of the reflection at grazing angle.
  102409. */
  102410. _this.reflectionReflectance0 = 0.05;
  102411. /**
  102412. * This specifies the weight of the reflection at a perpendicular point of view.
  102413. */
  102414. _this.reflectionReflectance90 = 0.5;
  102415. /**
  102416. * Helps to directly use the maps channels instead of their level.
  102417. */
  102418. _this.useRGBColor = true;
  102419. /**
  102420. * This helps reducing the banding effect that could occur on the background.
  102421. */
  102422. _this.enableNoise = false;
  102423. _this._fovMultiplier = 1.0;
  102424. /**
  102425. * Enable the FOV adjustment feature controlled by fovMultiplier.
  102426. */
  102427. _this.useEquirectangularFOV = false;
  102428. _this._maxSimultaneousLights = 4;
  102429. /**
  102430. * Number of Simultaneous lights allowed on the material.
  102431. */
  102432. _this.maxSimultaneousLights = 4;
  102433. /**
  102434. * Keep track of the image processing observer to allow dispose and replace.
  102435. */
  102436. _this._imageProcessingObserver = null;
  102437. /**
  102438. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  102439. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  102440. */
  102441. _this.switchToBGR = false;
  102442. // Temp values kept as cache in the material.
  102443. _this._renderTargets = new BABYLON.SmartArray(16);
  102444. _this._reflectionControls = BABYLON.Vector4.Zero();
  102445. _this._white = BABYLON.Color3.White();
  102446. _this._primaryShadowColor = BABYLON.Color3.Black();
  102447. _this._primaryHighlightColor = BABYLON.Color3.Black();
  102448. // Setup the default processing configuration to the scene.
  102449. _this._attachImageProcessingConfiguration(null);
  102450. _this.getRenderTargetTextures = function () {
  102451. _this._renderTargets.reset();
  102452. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  102453. _this._renderTargets.push(_this._diffuseTexture);
  102454. }
  102455. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  102456. _this._renderTargets.push(_this._reflectionTexture);
  102457. }
  102458. return _this._renderTargets;
  102459. };
  102460. return _this;
  102461. }
  102462. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  102463. /**
  102464. * Experimental Internal Use Only.
  102465. *
  102466. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  102467. * This acts as a helper to set the primary color to a more "human friendly" value.
  102468. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  102469. * output color as close as possible from the chosen value.
  102470. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  102471. * part of lighting setup.)
  102472. */
  102473. get: function () {
  102474. return this.__perceptualColor;
  102475. },
  102476. set: function (value) {
  102477. this.__perceptualColor = value;
  102478. this._computePrimaryColorFromPerceptualColor();
  102479. this._markAllSubMeshesAsLightsDirty();
  102480. },
  102481. enumerable: true,
  102482. configurable: true
  102483. });
  102484. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  102485. /**
  102486. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  102487. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  102488. */
  102489. get: function () {
  102490. return this._primaryColorShadowLevel;
  102491. },
  102492. set: function (value) {
  102493. this._primaryColorShadowLevel = value;
  102494. this._computePrimaryColors();
  102495. this._markAllSubMeshesAsLightsDirty();
  102496. },
  102497. enumerable: true,
  102498. configurable: true
  102499. });
  102500. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  102501. /**
  102502. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  102503. * The primary color is used at the level chosen to define what the white area would look.
  102504. */
  102505. get: function () {
  102506. return this._primaryColorHighlightLevel;
  102507. },
  102508. set: function (value) {
  102509. this._primaryColorHighlightLevel = value;
  102510. this._computePrimaryColors();
  102511. this._markAllSubMeshesAsLightsDirty();
  102512. },
  102513. enumerable: true,
  102514. configurable: true
  102515. });
  102516. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  102517. /**
  102518. * Sets the reflection reflectance fresnel values according to the default standard
  102519. * empirically know to work well :-)
  102520. */
  102521. set: function (value) {
  102522. var reflectionWeight = value;
  102523. if (reflectionWeight < 0.5) {
  102524. reflectionWeight = reflectionWeight * 2.0;
  102525. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  102526. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  102527. }
  102528. else {
  102529. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  102530. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  102531. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  102532. }
  102533. },
  102534. enumerable: true,
  102535. configurable: true
  102536. });
  102537. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  102538. /**
  102539. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102540. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  102541. * Recommended to be keep at 1.0 except for special cases.
  102542. */
  102543. get: function () {
  102544. return this._fovMultiplier;
  102545. },
  102546. set: function (value) {
  102547. if (isNaN(value)) {
  102548. value = 1.0;
  102549. }
  102550. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  102551. },
  102552. enumerable: true,
  102553. configurable: true
  102554. });
  102555. /**
  102556. * Attaches a new image processing configuration to the PBR Material.
  102557. * @param configuration (if null the scene configuration will be use)
  102558. */
  102559. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  102560. var _this = this;
  102561. if (configuration === this._imageProcessingConfiguration) {
  102562. return;
  102563. }
  102564. // Detaches observer.
  102565. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102566. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102567. }
  102568. // Pick the scene configuration if needed.
  102569. if (!configuration) {
  102570. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  102571. }
  102572. else {
  102573. this._imageProcessingConfiguration = configuration;
  102574. }
  102575. // Attaches observer.
  102576. if (this._imageProcessingConfiguration) {
  102577. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  102578. _this._computePrimaryColorFromPerceptualColor();
  102579. _this._markAllSubMeshesAsImageProcessingDirty();
  102580. });
  102581. }
  102582. };
  102583. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  102584. /**
  102585. * Gets the image processing configuration used either in this material.
  102586. */
  102587. get: function () {
  102588. return this._imageProcessingConfiguration;
  102589. },
  102590. /**
  102591. * Sets the Default image processing configuration used either in the this material.
  102592. *
  102593. * If sets to null, the scene one is in use.
  102594. */
  102595. set: function (value) {
  102596. this._attachImageProcessingConfiguration(value);
  102597. // Ensure the effect will be rebuilt.
  102598. this._markAllSubMeshesAsTexturesDirty();
  102599. },
  102600. enumerable: true,
  102601. configurable: true
  102602. });
  102603. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  102604. /**
  102605. * Gets wether the color curves effect is enabled.
  102606. */
  102607. get: function () {
  102608. return this.imageProcessingConfiguration.colorCurvesEnabled;
  102609. },
  102610. /**
  102611. * Sets wether the color curves effect is enabled.
  102612. */
  102613. set: function (value) {
  102614. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  102615. },
  102616. enumerable: true,
  102617. configurable: true
  102618. });
  102619. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  102620. /**
  102621. * Gets wether the color grading effect is enabled.
  102622. */
  102623. get: function () {
  102624. return this.imageProcessingConfiguration.colorGradingEnabled;
  102625. },
  102626. /**
  102627. * Gets wether the color grading effect is enabled.
  102628. */
  102629. set: function (value) {
  102630. this.imageProcessingConfiguration.colorGradingEnabled = value;
  102631. },
  102632. enumerable: true,
  102633. configurable: true
  102634. });
  102635. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  102636. /**
  102637. * Gets wether tonemapping is enabled or not.
  102638. */
  102639. get: function () {
  102640. return this._imageProcessingConfiguration.toneMappingEnabled;
  102641. },
  102642. /**
  102643. * Sets wether tonemapping is enabled or not
  102644. */
  102645. set: function (value) {
  102646. this._imageProcessingConfiguration.toneMappingEnabled = value;
  102647. },
  102648. enumerable: true,
  102649. configurable: true
  102650. });
  102651. ;
  102652. ;
  102653. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  102654. /**
  102655. * The camera exposure used on this material.
  102656. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102657. * This corresponds to a photographic exposure.
  102658. */
  102659. get: function () {
  102660. return this._imageProcessingConfiguration.exposure;
  102661. },
  102662. /**
  102663. * The camera exposure used on this material.
  102664. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102665. * This corresponds to a photographic exposure.
  102666. */
  102667. set: function (value) {
  102668. this._imageProcessingConfiguration.exposure = value;
  102669. },
  102670. enumerable: true,
  102671. configurable: true
  102672. });
  102673. ;
  102674. ;
  102675. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  102676. /**
  102677. * Gets The camera contrast used on this material.
  102678. */
  102679. get: function () {
  102680. return this._imageProcessingConfiguration.contrast;
  102681. },
  102682. /**
  102683. * Sets The camera contrast used on this material.
  102684. */
  102685. set: function (value) {
  102686. this._imageProcessingConfiguration.contrast = value;
  102687. },
  102688. enumerable: true,
  102689. configurable: true
  102690. });
  102691. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  102692. /**
  102693. * Gets the Color Grading 2D Lookup Texture.
  102694. */
  102695. get: function () {
  102696. return this._imageProcessingConfiguration.colorGradingTexture;
  102697. },
  102698. /**
  102699. * Sets the Color Grading 2D Lookup Texture.
  102700. */
  102701. set: function (value) {
  102702. this.imageProcessingConfiguration.colorGradingTexture = value;
  102703. },
  102704. enumerable: true,
  102705. configurable: true
  102706. });
  102707. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  102708. /**
  102709. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102710. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102711. * 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;
  102712. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102713. */
  102714. get: function () {
  102715. return this.imageProcessingConfiguration.colorCurves;
  102716. },
  102717. /**
  102718. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102719. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102720. * 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;
  102721. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102722. */
  102723. set: function (value) {
  102724. this.imageProcessingConfiguration.colorCurves = value;
  102725. },
  102726. enumerable: true,
  102727. configurable: true
  102728. });
  102729. /**
  102730. * The entire material has been created in order to prevent overdraw.
  102731. * @returns false
  102732. */
  102733. BackgroundMaterial.prototype.needAlphaTesting = function () {
  102734. return true;
  102735. };
  102736. /**
  102737. * The entire material has been created in order to prevent overdraw.
  102738. * @returns true if blending is enable
  102739. */
  102740. BackgroundMaterial.prototype.needAlphaBlending = function () {
  102741. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  102742. };
  102743. /**
  102744. * Checks wether the material is ready to be rendered for a given mesh.
  102745. * @param mesh The mesh to render
  102746. * @param subMesh The submesh to check against
  102747. * @param useInstances Specify wether or not the material is used with instances
  102748. * @returns true if all the dependencies are ready (Textures, Effects...)
  102749. */
  102750. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  102751. var _this = this;
  102752. if (useInstances === void 0) { useInstances = false; }
  102753. if (subMesh.effect && this.isFrozen) {
  102754. if (this._wasPreviouslyReady) {
  102755. return true;
  102756. }
  102757. }
  102758. if (!subMesh._materialDefines) {
  102759. subMesh._materialDefines = new BackgroundMaterialDefines();
  102760. }
  102761. var scene = this.getScene();
  102762. var defines = subMesh._materialDefines;
  102763. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  102764. if (defines._renderId === scene.getRenderId()) {
  102765. return true;
  102766. }
  102767. }
  102768. var engine = scene.getEngine();
  102769. // Lights
  102770. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  102771. defines._needNormals = true;
  102772. // Textures
  102773. if (defines._areTexturesDirty) {
  102774. defines._needUVs = false;
  102775. if (scene.texturesEnabled) {
  102776. if (scene.getEngine().getCaps().textureLOD) {
  102777. defines.TEXTURELODSUPPORT = true;
  102778. }
  102779. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102780. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  102781. return false;
  102782. }
  102783. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  102784. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  102785. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  102786. defines.OPACITYFRESNEL = this._opacityFresnel;
  102787. }
  102788. else {
  102789. defines.DIFFUSE = false;
  102790. defines.DIFFUSEHASALPHA = false;
  102791. defines.GAMMADIFFUSE = false;
  102792. defines.OPACITYFRESNEL = false;
  102793. }
  102794. var reflectionTexture = this._reflectionTexture;
  102795. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102796. if (!reflectionTexture.isReadyOrNotBlocking()) {
  102797. return false;
  102798. }
  102799. defines.REFLECTION = true;
  102800. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  102801. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  102802. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  102803. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  102804. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  102805. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  102806. defines.REFLECTIONBGR = this.switchToBGR;
  102807. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  102808. defines.INVERTCUBICMAP = true;
  102809. }
  102810. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  102811. switch (reflectionTexture.coordinatesMode) {
  102812. case BABYLON.Texture.EXPLICIT_MODE:
  102813. defines.REFLECTIONMAP_EXPLICIT = true;
  102814. break;
  102815. case BABYLON.Texture.PLANAR_MODE:
  102816. defines.REFLECTIONMAP_PLANAR = true;
  102817. break;
  102818. case BABYLON.Texture.PROJECTION_MODE:
  102819. defines.REFLECTIONMAP_PROJECTION = true;
  102820. break;
  102821. case BABYLON.Texture.SKYBOX_MODE:
  102822. defines.REFLECTIONMAP_SKYBOX = true;
  102823. break;
  102824. case BABYLON.Texture.SPHERICAL_MODE:
  102825. defines.REFLECTIONMAP_SPHERICAL = true;
  102826. break;
  102827. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  102828. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  102829. break;
  102830. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  102831. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  102832. break;
  102833. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  102834. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  102835. break;
  102836. case BABYLON.Texture.CUBIC_MODE:
  102837. case BABYLON.Texture.INVCUBIC_MODE:
  102838. default:
  102839. defines.REFLECTIONMAP_CUBIC = true;
  102840. break;
  102841. }
  102842. if (this.reflectionFresnel) {
  102843. defines.REFLECTIONFRESNEL = true;
  102844. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  102845. this._reflectionControls.x = this.reflectionAmount;
  102846. this._reflectionControls.y = this.reflectionReflectance0;
  102847. this._reflectionControls.z = this.reflectionReflectance90;
  102848. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  102849. }
  102850. else {
  102851. defines.REFLECTIONFRESNEL = false;
  102852. defines.REFLECTIONFALLOFF = false;
  102853. }
  102854. }
  102855. else {
  102856. defines.REFLECTION = false;
  102857. defines.REFLECTIONFRESNEL = false;
  102858. defines.REFLECTIONFALLOFF = false;
  102859. defines.REFLECTIONBLUR = false;
  102860. defines.REFLECTIONMAP_3D = false;
  102861. defines.REFLECTIONMAP_SPHERICAL = false;
  102862. defines.REFLECTIONMAP_PLANAR = false;
  102863. defines.REFLECTIONMAP_CUBIC = false;
  102864. defines.REFLECTIONMAP_PROJECTION = false;
  102865. defines.REFLECTIONMAP_SKYBOX = false;
  102866. defines.REFLECTIONMAP_EXPLICIT = false;
  102867. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102868. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102869. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102870. defines.INVERTCUBICMAP = false;
  102871. defines.REFLECTIONMAP_OPPOSITEZ = false;
  102872. defines.LODINREFLECTIONALPHA = false;
  102873. defines.GAMMAREFLECTION = false;
  102874. defines.RGBDREFLECTION = false;
  102875. }
  102876. }
  102877. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  102878. defines.USERGBCOLOR = this._useRGBColor;
  102879. defines.NOISE = this._enableNoise;
  102880. }
  102881. if (defines._areLightsDirty) {
  102882. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  102883. }
  102884. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  102885. if (!this._imageProcessingConfiguration.isReady()) {
  102886. return false;
  102887. }
  102888. this._imageProcessingConfiguration.prepareDefines(defines);
  102889. }
  102890. // Misc.
  102891. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  102892. // Values that need to be evaluated on every frame
  102893. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  102894. // Attribs
  102895. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  102896. if (mesh) {
  102897. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102898. mesh.createNormals(true);
  102899. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  102900. }
  102901. }
  102902. }
  102903. // Get correct effect
  102904. if (defines.isDirty) {
  102905. defines.markAsProcessed();
  102906. scene.resetCachedMaterial();
  102907. // Fallbacks
  102908. var fallbacks = new BABYLON.EffectFallbacks();
  102909. if (defines.FOG) {
  102910. fallbacks.addFallback(0, "FOG");
  102911. }
  102912. if (defines.POINTSIZE) {
  102913. fallbacks.addFallback(1, "POINTSIZE");
  102914. }
  102915. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  102916. if (defines.NUM_BONE_INFLUENCERS > 0) {
  102917. fallbacks.addCPUSkinningFallback(0, mesh);
  102918. }
  102919. //Attributes
  102920. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102921. if (defines.NORMAL) {
  102922. attribs.push(BABYLON.VertexBuffer.NormalKind);
  102923. }
  102924. if (defines.UV1) {
  102925. attribs.push(BABYLON.VertexBuffer.UVKind);
  102926. }
  102927. if (defines.UV2) {
  102928. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102929. }
  102930. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  102931. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  102932. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  102933. "vFogInfos", "vFogColor", "pointSize",
  102934. "vClipPlane", "mBones",
  102935. "vPrimaryColor", "vPrimaryColorShadow",
  102936. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  102937. "shadowLevel", "alpha",
  102938. "vBackgroundCenter", "vReflectionControl",
  102939. "vDiffuseInfos", "diffuseMatrix",
  102940. ];
  102941. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  102942. var uniformBuffers = ["Material", "Scene"];
  102943. if (BABYLON.ImageProcessingConfiguration) {
  102944. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  102945. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  102946. }
  102947. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  102948. uniformsNames: uniforms,
  102949. uniformBuffersNames: uniformBuffers,
  102950. samplers: samplers,
  102951. defines: defines,
  102952. maxSimultaneousLights: this._maxSimultaneousLights
  102953. });
  102954. var onCompiled = function (effect) {
  102955. if (_this.onCompiled) {
  102956. _this.onCompiled(effect);
  102957. }
  102958. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  102959. };
  102960. var join = defines.toString();
  102961. subMesh.setEffect(scene.getEngine().createEffect("background", {
  102962. attributes: attribs,
  102963. uniformsNames: uniforms,
  102964. uniformBuffersNames: uniformBuffers,
  102965. samplers: samplers,
  102966. defines: join,
  102967. fallbacks: fallbacks,
  102968. onCompiled: onCompiled,
  102969. onError: this.onError,
  102970. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  102971. }, engine), defines);
  102972. this.buildUniformLayout();
  102973. }
  102974. if (!subMesh.effect || !subMesh.effect.isReady()) {
  102975. return false;
  102976. }
  102977. defines._renderId = scene.getRenderId();
  102978. this._wasPreviouslyReady = true;
  102979. return true;
  102980. };
  102981. /**
  102982. * Compute the primary color according to the chosen perceptual color.
  102983. */
  102984. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  102985. if (!this.__perceptualColor) {
  102986. return;
  102987. }
  102988. this._primaryColor.copyFrom(this.__perceptualColor);
  102989. // Revert gamma space.
  102990. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  102991. // Revert image processing configuration.
  102992. if (this._imageProcessingConfiguration) {
  102993. // Revert Exposure.
  102994. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  102995. }
  102996. this._computePrimaryColors();
  102997. };
  102998. /**
  102999. * Compute the highlights and shadow colors according to their chosen levels.
  103000. */
  103001. BackgroundMaterial.prototype._computePrimaryColors = function () {
  103002. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  103003. return;
  103004. }
  103005. // Find the highlight color based on the configuration.
  103006. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  103007. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  103008. // Find the shadow color based on the configuration.
  103009. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  103010. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  103011. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  103012. };
  103013. /**
  103014. * Build the uniform buffer used in the material.
  103015. */
  103016. BackgroundMaterial.prototype.buildUniformLayout = function () {
  103017. // Order is important !
  103018. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  103019. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  103020. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  103021. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  103022. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  103023. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  103024. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  103025. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  103026. this._uniformBuffer.addUniform("pointSize", 1);
  103027. this._uniformBuffer.addUniform("shadowLevel", 1);
  103028. this._uniformBuffer.addUniform("alpha", 1);
  103029. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  103030. this._uniformBuffer.addUniform("vReflectionControl", 4);
  103031. this._uniformBuffer.create();
  103032. };
  103033. /**
  103034. * Unbind the material.
  103035. */
  103036. BackgroundMaterial.prototype.unbind = function () {
  103037. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  103038. this._uniformBuffer.setTexture("diffuseSampler", null);
  103039. }
  103040. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  103041. this._uniformBuffer.setTexture("reflectionSampler", null);
  103042. }
  103043. _super.prototype.unbind.call(this);
  103044. };
  103045. /**
  103046. * Bind only the world matrix to the material.
  103047. * @param world The world matrix to bind.
  103048. */
  103049. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  103050. this._activeEffect.setMatrix("world", world);
  103051. };
  103052. /**
  103053. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  103054. * @param world The world matrix to bind.
  103055. * @param subMesh The submesh to bind for.
  103056. */
  103057. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  103058. var scene = this.getScene();
  103059. var defines = subMesh._materialDefines;
  103060. if (!defines) {
  103061. return;
  103062. }
  103063. var effect = subMesh.effect;
  103064. if (!effect) {
  103065. return;
  103066. }
  103067. this._activeEffect = effect;
  103068. // Matrices
  103069. this.bindOnlyWorldMatrix(world);
  103070. // Bones
  103071. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  103072. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  103073. if (mustRebind) {
  103074. this._uniformBuffer.bindToEffect(effect, "Material");
  103075. this.bindViewProjection(effect);
  103076. var reflectionTexture = this._reflectionTexture;
  103077. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  103078. // Texture uniforms
  103079. if (scene.texturesEnabled) {
  103080. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103081. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  103082. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  103083. }
  103084. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103085. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  103086. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  103087. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  103088. }
  103089. }
  103090. if (this.shadowLevel > 0) {
  103091. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  103092. }
  103093. this._uniformBuffer.updateFloat("alpha", this.alpha);
  103094. // Point size
  103095. if (this.pointsCloud) {
  103096. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  103097. }
  103098. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  103099. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  103100. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  103101. }
  103102. else {
  103103. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  103104. }
  103105. }
  103106. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  103107. // Textures
  103108. if (scene.texturesEnabled) {
  103109. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103110. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  103111. }
  103112. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103113. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  103114. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103115. }
  103116. else if (!defines.REFLECTIONBLUR) {
  103117. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103118. }
  103119. else {
  103120. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  103121. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  103122. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  103123. }
  103124. if (defines.REFLECTIONFRESNEL) {
  103125. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  103126. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  103127. }
  103128. }
  103129. }
  103130. // Clip plane
  103131. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  103132. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  103133. }
  103134. if (mustRebind || !this.isFrozen) {
  103135. if (scene.lightsEnabled) {
  103136. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  103137. }
  103138. // View
  103139. this.bindView(effect);
  103140. // Fog
  103141. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  103142. // image processing
  103143. if (this._imageProcessingConfiguration) {
  103144. this._imageProcessingConfiguration.bind(this._activeEffect);
  103145. }
  103146. }
  103147. this._uniformBuffer.update();
  103148. this._afterBind(mesh, this._activeEffect);
  103149. };
  103150. /**
  103151. * Dispose the material.
  103152. * @param forceDisposeEffect Force disposal of the associated effect.
  103153. * @param forceDisposeTextures Force disposal of the associated textures.
  103154. */
  103155. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  103156. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  103157. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  103158. if (forceDisposeTextures) {
  103159. if (this.diffuseTexture) {
  103160. this.diffuseTexture.dispose();
  103161. }
  103162. if (this.reflectionTexture) {
  103163. this.reflectionTexture.dispose();
  103164. }
  103165. }
  103166. this._renderTargets.dispose();
  103167. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  103168. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  103169. }
  103170. _super.prototype.dispose.call(this, forceDisposeEffect);
  103171. };
  103172. /**
  103173. * Clones the material.
  103174. * @param name The cloned name.
  103175. * @returns The cloned material.
  103176. */
  103177. BackgroundMaterial.prototype.clone = function (name) {
  103178. var _this = this;
  103179. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  103180. };
  103181. /**
  103182. * Serializes the current material to its JSON representation.
  103183. * @returns The JSON representation.
  103184. */
  103185. BackgroundMaterial.prototype.serialize = function () {
  103186. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103187. serializationObject.customType = "BABYLON.BackgroundMaterial";
  103188. return serializationObject;
  103189. };
  103190. /**
  103191. * Gets the class name of the material
  103192. * @returns "BackgroundMaterial"
  103193. */
  103194. BackgroundMaterial.prototype.getClassName = function () {
  103195. return "BackgroundMaterial";
  103196. };
  103197. /**
  103198. * Parse a JSON input to create back a background material.
  103199. * @param source The JSON data to parse
  103200. * @param scene The scene to create the parsed material in
  103201. * @param rootUrl The root url of the assets the material depends upon
  103202. * @returns the instantiated BackgroundMaterial.
  103203. */
  103204. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  103205. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  103206. };
  103207. /**
  103208. * Standard reflectance value at parallel view angle.
  103209. */
  103210. BackgroundMaterial.StandardReflectance0 = 0.05;
  103211. /**
  103212. * Standard reflectance value at grazing angle.
  103213. */
  103214. BackgroundMaterial.StandardReflectance90 = 0.5;
  103215. __decorate([
  103216. BABYLON.serializeAsColor3()
  103217. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  103218. __decorate([
  103219. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103220. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  103221. __decorate([
  103222. BABYLON.serializeAsColor3()
  103223. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  103224. __decorate([
  103225. BABYLON.serialize()
  103226. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  103227. __decorate([
  103228. BABYLON.serialize()
  103229. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  103230. __decorate([
  103231. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103232. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  103233. __decorate([
  103234. BABYLON.serializeAsTexture()
  103235. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  103236. __decorate([
  103237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103238. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  103239. __decorate([
  103240. BABYLON.serialize()
  103241. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  103242. __decorate([
  103243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103244. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  103245. __decorate([
  103246. BABYLON.serializeAsTexture()
  103247. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  103248. __decorate([
  103249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103250. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  103251. __decorate([
  103252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103253. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  103254. __decorate([
  103255. BABYLON.serialize()
  103256. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  103257. __decorate([
  103258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103259. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  103260. __decorate([
  103261. BABYLON.serializeAsVector3()
  103262. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  103263. __decorate([
  103264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103265. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  103266. __decorate([
  103267. BABYLON.serialize()
  103268. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  103269. __decorate([
  103270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103271. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  103272. __decorate([
  103273. BABYLON.serialize()
  103274. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  103275. __decorate([
  103276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103277. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  103278. __decorate([
  103279. BABYLON.serialize()
  103280. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  103281. __decorate([
  103282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103283. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  103284. __decorate([
  103285. BABYLON.serialize()
  103286. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  103287. __decorate([
  103288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103289. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  103290. __decorate([
  103291. BABYLON.serialize()
  103292. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  103293. __decorate([
  103294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103295. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  103296. __decorate([
  103297. BABYLON.serialize()
  103298. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  103299. __decorate([
  103300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103301. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  103302. __decorate([
  103303. BABYLON.serialize()
  103304. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  103305. __decorate([
  103306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103307. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  103308. __decorate([
  103309. BABYLON.serialize()
  103310. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  103311. __decorate([
  103312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103313. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  103314. __decorate([
  103315. BABYLON.serialize()
  103316. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  103317. __decorate([
  103318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103319. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  103320. __decorate([
  103321. BABYLON.serializeAsImageProcessingConfiguration()
  103322. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  103323. return BackgroundMaterial;
  103324. }(BABYLON.PushMaterial));
  103325. BABYLON.BackgroundMaterial = BackgroundMaterial;
  103326. })(BABYLON || (BABYLON = {}));
  103327. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  103328. var __assign = (this && this.__assign) || Object.assign || function(t) {
  103329. for (var s, i = 1, n = arguments.length; i < n; i++) {
  103330. s = arguments[i];
  103331. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  103332. t[p] = s[p];
  103333. }
  103334. return t;
  103335. };
  103336. var BABYLON;
  103337. (function (BABYLON) {
  103338. /**
  103339. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  103340. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  103341. * It also helps with the default setup of your imageProcessing configuration.
  103342. */
  103343. var EnvironmentHelper = /** @class */ (function () {
  103344. /**
  103345. * constructor
  103346. * @param options
  103347. * @param scene The scene to add the material to
  103348. */
  103349. function EnvironmentHelper(options, scene) {
  103350. var _this = this;
  103351. this._errorHandler = function (message, exception) {
  103352. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  103353. };
  103354. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  103355. this._scene = scene;
  103356. this.onErrorObservable = new BABYLON.Observable();
  103357. this._setupBackground();
  103358. this._setupImageProcessing();
  103359. }
  103360. /**
  103361. * Creates the default options for the helper.
  103362. */
  103363. EnvironmentHelper._getDefaultOptions = function () {
  103364. return {
  103365. createGround: true,
  103366. groundSize: 15,
  103367. groundTexture: this._groundTextureCDNUrl,
  103368. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  103369. groundOpacity: 0.9,
  103370. enableGroundShadow: true,
  103371. groundShadowLevel: 0.5,
  103372. enableGroundMirror: false,
  103373. groundMirrorSizeRatio: 0.3,
  103374. groundMirrorBlurKernel: 64,
  103375. groundMirrorAmount: 1,
  103376. groundMirrorFresnelWeight: 1,
  103377. groundMirrorFallOffDistance: 0,
  103378. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  103379. groundYBias: 0.00001,
  103380. createSkybox: true,
  103381. skyboxSize: 20,
  103382. skyboxTexture: this._skyboxTextureCDNUrl,
  103383. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  103384. backgroundYRotation: 0,
  103385. sizeAuto: true,
  103386. rootPosition: BABYLON.Vector3.Zero(),
  103387. setupImageProcessing: true,
  103388. environmentTexture: this._environmentTextureCDNUrl,
  103389. cameraExposure: 0.8,
  103390. cameraContrast: 1.2,
  103391. toneMappingEnabled: true,
  103392. };
  103393. };
  103394. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  103395. /**
  103396. * Gets the root mesh created by the helper.
  103397. */
  103398. get: function () {
  103399. return this._rootMesh;
  103400. },
  103401. enumerable: true,
  103402. configurable: true
  103403. });
  103404. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  103405. /**
  103406. * Gets the skybox created by the helper.
  103407. */
  103408. get: function () {
  103409. return this._skybox;
  103410. },
  103411. enumerable: true,
  103412. configurable: true
  103413. });
  103414. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  103415. /**
  103416. * Gets the skybox texture created by the helper.
  103417. */
  103418. get: function () {
  103419. return this._skyboxTexture;
  103420. },
  103421. enumerable: true,
  103422. configurable: true
  103423. });
  103424. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  103425. /**
  103426. * Gets the skybox material created by the helper.
  103427. */
  103428. get: function () {
  103429. return this._skyboxMaterial;
  103430. },
  103431. enumerable: true,
  103432. configurable: true
  103433. });
  103434. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  103435. /**
  103436. * Gets the ground mesh created by the helper.
  103437. */
  103438. get: function () {
  103439. return this._ground;
  103440. },
  103441. enumerable: true,
  103442. configurable: true
  103443. });
  103444. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  103445. /**
  103446. * Gets the ground texture created by the helper.
  103447. */
  103448. get: function () {
  103449. return this._groundTexture;
  103450. },
  103451. enumerable: true,
  103452. configurable: true
  103453. });
  103454. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  103455. /**
  103456. * Gets the ground mirror created by the helper.
  103457. */
  103458. get: function () {
  103459. return this._groundMirror;
  103460. },
  103461. enumerable: true,
  103462. configurable: true
  103463. });
  103464. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  103465. /**
  103466. * Gets the ground mirror render list to helps pushing the meshes
  103467. * you wish in the ground reflection.
  103468. */
  103469. get: function () {
  103470. if (this._groundMirror) {
  103471. return this._groundMirror.renderList;
  103472. }
  103473. return null;
  103474. },
  103475. enumerable: true,
  103476. configurable: true
  103477. });
  103478. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  103479. /**
  103480. * Gets the ground material created by the helper.
  103481. */
  103482. get: function () {
  103483. return this._groundMaterial;
  103484. },
  103485. enumerable: true,
  103486. configurable: true
  103487. });
  103488. /**
  103489. * Updates the background according to the new options
  103490. * @param options
  103491. */
  103492. EnvironmentHelper.prototype.updateOptions = function (options) {
  103493. var newOptions = __assign({}, this._options, options);
  103494. if (this._ground && !newOptions.createGround) {
  103495. this._ground.dispose();
  103496. this._ground = null;
  103497. }
  103498. if (this._groundMaterial && !newOptions.createGround) {
  103499. this._groundMaterial.dispose();
  103500. this._groundMaterial = null;
  103501. }
  103502. if (this._groundTexture) {
  103503. if (this._options.groundTexture != newOptions.groundTexture) {
  103504. this._groundTexture.dispose();
  103505. this._groundTexture = null;
  103506. }
  103507. }
  103508. if (this._skybox && !newOptions.createSkybox) {
  103509. this._skybox.dispose();
  103510. this._skybox = null;
  103511. }
  103512. if (this._skyboxMaterial && !newOptions.createSkybox) {
  103513. this._skyboxMaterial.dispose();
  103514. this._skyboxMaterial = null;
  103515. }
  103516. if (this._skyboxTexture) {
  103517. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  103518. this._skyboxTexture.dispose();
  103519. this._skyboxTexture = null;
  103520. }
  103521. }
  103522. if (this._groundMirror && !newOptions.enableGroundMirror) {
  103523. this._groundMirror.dispose();
  103524. this._groundMirror = null;
  103525. }
  103526. if (this._scene.environmentTexture) {
  103527. if (this._options.environmentTexture != newOptions.environmentTexture) {
  103528. this._scene.environmentTexture.dispose();
  103529. }
  103530. }
  103531. this._options = newOptions;
  103532. this._setupBackground();
  103533. this._setupImageProcessing();
  103534. };
  103535. /**
  103536. * Sets the primary color of all the available elements.
  103537. * @param color the main color to affect to the ground and the background
  103538. */
  103539. EnvironmentHelper.prototype.setMainColor = function (color) {
  103540. if (this.groundMaterial) {
  103541. this.groundMaterial.primaryColor = color;
  103542. }
  103543. if (this.skyboxMaterial) {
  103544. this.skyboxMaterial.primaryColor = color;
  103545. }
  103546. if (this.groundMirror) {
  103547. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  103548. }
  103549. };
  103550. /**
  103551. * Setup the image processing according to the specified options.
  103552. */
  103553. EnvironmentHelper.prototype._setupImageProcessing = function () {
  103554. if (this._options.setupImageProcessing) {
  103555. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  103556. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  103557. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  103558. this._setupEnvironmentTexture();
  103559. }
  103560. };
  103561. /**
  103562. * Setup the environment texture according to the specified options.
  103563. */
  103564. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  103565. if (this._scene.environmentTexture) {
  103566. return;
  103567. }
  103568. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  103569. this._scene.environmentTexture = this._options.environmentTexture;
  103570. return;
  103571. }
  103572. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  103573. this._scene.environmentTexture = environmentTexture;
  103574. };
  103575. /**
  103576. * Setup the background according to the specified options.
  103577. */
  103578. EnvironmentHelper.prototype._setupBackground = function () {
  103579. if (!this._rootMesh) {
  103580. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  103581. }
  103582. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  103583. var sceneSize = this._getSceneSize();
  103584. if (this._options.createGround) {
  103585. this._setupGround(sceneSize);
  103586. this._setupGroundMaterial();
  103587. this._setupGroundDiffuseTexture();
  103588. if (this._options.enableGroundMirror) {
  103589. this._setupGroundMirrorTexture(sceneSize);
  103590. }
  103591. this._setupMirrorInGroundMaterial();
  103592. }
  103593. if (this._options.createSkybox) {
  103594. this._setupSkybox(sceneSize);
  103595. this._setupSkyboxMaterial();
  103596. this._setupSkyboxReflectionTexture();
  103597. }
  103598. this._rootMesh.position.x = sceneSize.rootPosition.x;
  103599. this._rootMesh.position.z = sceneSize.rootPosition.z;
  103600. this._rootMesh.position.y = sceneSize.rootPosition.y;
  103601. };
  103602. /**
  103603. * Get the scene sizes according to the setup.
  103604. */
  103605. EnvironmentHelper.prototype._getSceneSize = function () {
  103606. var _this = this;
  103607. var groundSize = this._options.groundSize;
  103608. var skyboxSize = this._options.skyboxSize;
  103609. var rootPosition = this._options.rootPosition;
  103610. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  103611. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103612. }
  103613. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  103614. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  103615. });
  103616. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  103617. if (this._options.sizeAuto) {
  103618. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  103619. this._scene.activeCamera.upperRadiusLimit) {
  103620. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  103621. skyboxSize = groundSize;
  103622. }
  103623. var sceneDiagonalLenght = sceneDiagonal.length();
  103624. if (sceneDiagonalLenght > groundSize) {
  103625. groundSize = sceneDiagonalLenght * 2;
  103626. skyboxSize = groundSize;
  103627. }
  103628. // 10 % bigger.
  103629. groundSize *= 1.1;
  103630. skyboxSize *= 1.5;
  103631. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  103632. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  103633. }
  103634. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103635. };
  103636. /**
  103637. * Setup the ground according to the specified options.
  103638. */
  103639. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  103640. var _this = this;
  103641. if (!this._ground || this._ground.isDisposed()) {
  103642. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  103643. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  103644. this._ground.parent = this._rootMesh;
  103645. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  103646. }
  103647. this._ground.receiveShadows = this._options.enableGroundShadow;
  103648. };
  103649. /**
  103650. * Setup the ground material according to the specified options.
  103651. */
  103652. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  103653. if (!this._groundMaterial) {
  103654. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  103655. }
  103656. this._groundMaterial.alpha = this._options.groundOpacity;
  103657. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  103658. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  103659. this._groundMaterial.primaryColor = this._options.groundColor;
  103660. this._groundMaterial.useRGBColor = false;
  103661. this._groundMaterial.enableNoise = true;
  103662. if (this._ground) {
  103663. this._ground.material = this._groundMaterial;
  103664. }
  103665. };
  103666. /**
  103667. * Setup the ground diffuse texture according to the specified options.
  103668. */
  103669. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  103670. if (!this._groundMaterial) {
  103671. return;
  103672. }
  103673. if (this._groundTexture) {
  103674. return;
  103675. }
  103676. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  103677. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  103678. return;
  103679. }
  103680. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103681. diffuseTexture.gammaSpace = false;
  103682. diffuseTexture.hasAlpha = true;
  103683. this._groundMaterial.diffuseTexture = diffuseTexture;
  103684. };
  103685. /**
  103686. * Setup the ground mirror texture according to the specified options.
  103687. */
  103688. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  103689. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103690. if (!this._groundMirror) {
  103691. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  103692. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  103693. this._groundMirror.anisotropicFilteringLevel = 1;
  103694. this._groundMirror.wrapU = wrapping;
  103695. this._groundMirror.wrapV = wrapping;
  103696. this._groundMirror.gammaSpace = false;
  103697. if (this._groundMirror.renderList) {
  103698. for (var i = 0; i < this._scene.meshes.length; i++) {
  103699. var mesh = this._scene.meshes[i];
  103700. if (mesh !== this._ground &&
  103701. mesh !== this._skybox &&
  103702. mesh !== this._rootMesh) {
  103703. this._groundMirror.renderList.push(mesh);
  103704. }
  103705. }
  103706. }
  103707. }
  103708. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  103709. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  103710. };
  103711. /**
  103712. * Setup the ground to receive the mirror texture.
  103713. */
  103714. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  103715. if (this._groundMaterial) {
  103716. this._groundMaterial.reflectionTexture = this._groundMirror;
  103717. this._groundMaterial.reflectionFresnel = true;
  103718. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  103719. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  103720. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  103721. }
  103722. };
  103723. /**
  103724. * Setup the skybox according to the specified options.
  103725. */
  103726. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  103727. var _this = this;
  103728. if (!this._skybox || this._skybox.isDisposed()) {
  103729. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  103730. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  103731. }
  103732. this._skybox.parent = this._rootMesh;
  103733. };
  103734. /**
  103735. * Setup the skybox material according to the specified options.
  103736. */
  103737. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  103738. if (!this._skybox) {
  103739. return;
  103740. }
  103741. if (!this._skyboxMaterial) {
  103742. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  103743. }
  103744. this._skyboxMaterial.useRGBColor = false;
  103745. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  103746. this._skyboxMaterial.enableNoise = true;
  103747. this._skybox.material = this._skyboxMaterial;
  103748. };
  103749. /**
  103750. * Setup the skybox reflection texture according to the specified options.
  103751. */
  103752. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  103753. if (!this._skyboxMaterial) {
  103754. return;
  103755. }
  103756. if (this._skyboxTexture) {
  103757. return;
  103758. }
  103759. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  103760. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  103761. return;
  103762. }
  103763. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103764. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  103765. this._skyboxTexture.gammaSpace = false;
  103766. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  103767. };
  103768. /**
  103769. * Dispose all the elements created by the Helper.
  103770. */
  103771. EnvironmentHelper.prototype.dispose = function () {
  103772. if (this._groundMaterial) {
  103773. this._groundMaterial.dispose(true, true);
  103774. }
  103775. if (this._skyboxMaterial) {
  103776. this._skyboxMaterial.dispose(true, true);
  103777. }
  103778. this._rootMesh.dispose(false);
  103779. };
  103780. /**
  103781. * Default ground texture URL.
  103782. */
  103783. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  103784. /**
  103785. * Default skybox texture URL.
  103786. */
  103787. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  103788. /**
  103789. * Default environment texture URL.
  103790. */
  103791. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  103792. return EnvironmentHelper;
  103793. }());
  103794. BABYLON.EnvironmentHelper = EnvironmentHelper;
  103795. })(BABYLON || (BABYLON = {}));
  103796. //# sourceMappingURL=babylon.environmentHelper.js.map
  103797. var BABYLON;
  103798. (function (BABYLON) {
  103799. /** Internal class used to store shapes for emitters */
  103800. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  103801. function ParticleSystemSetEmitterCreationOptions() {
  103802. }
  103803. return ParticleSystemSetEmitterCreationOptions;
  103804. }());
  103805. /**
  103806. * Represents a set of particle systems working together to create a specific effect
  103807. */
  103808. var ParticleSystemSet = /** @class */ (function () {
  103809. function ParticleSystemSet() {
  103810. /**
  103811. * Gets the particle system list
  103812. */
  103813. this.systems = new Array();
  103814. }
  103815. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  103816. /**
  103817. * Gets the emitter node used with this set
  103818. */
  103819. get: function () {
  103820. return this._emitterNode;
  103821. },
  103822. enumerable: true,
  103823. configurable: true
  103824. });
  103825. /**
  103826. * Creates a new emitter mesh as a sphere
  103827. * @param options defines the options used to create the sphere
  103828. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  103829. * @param scene defines the hosting scene
  103830. */
  103831. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  103832. if (this._emitterNode) {
  103833. this._emitterNode.dispose();
  103834. }
  103835. this._emitterCreationOptions = {
  103836. kind: "Sphere",
  103837. options: options,
  103838. renderingGroupId: renderingGroupId
  103839. };
  103840. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  103841. emitterMesh.renderingGroupId = renderingGroupId;
  103842. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  103843. material.emissiveColor = options.color;
  103844. emitterMesh.material = material;
  103845. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103846. var system = _a[_i];
  103847. system.emitter = emitterMesh;
  103848. }
  103849. this._emitterNode = emitterMesh;
  103850. };
  103851. /**
  103852. * Starts all particle systems of the set
  103853. * @param emitter defines an optional mesh to use as emitter for the particle systems
  103854. */
  103855. ParticleSystemSet.prototype.start = function (emitter) {
  103856. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103857. var system = _a[_i];
  103858. if (emitter) {
  103859. system.emitter = emitter;
  103860. }
  103861. system.start();
  103862. }
  103863. };
  103864. /**
  103865. * Release all associated resources
  103866. */
  103867. ParticleSystemSet.prototype.dispose = function () {
  103868. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103869. var system = _a[_i];
  103870. system.dispose();
  103871. }
  103872. this.systems = [];
  103873. if (this._emitterNode) {
  103874. this._emitterNode.dispose();
  103875. this._emitterNode = null;
  103876. }
  103877. };
  103878. /**
  103879. * Serialize the set into a JSON compatible object
  103880. * @returns a JSON compatible representation of the set
  103881. */
  103882. ParticleSystemSet.prototype.serialize = function () {
  103883. var result = {};
  103884. result.systems = [];
  103885. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103886. var system = _a[_i];
  103887. result.systems.push(system.serialize());
  103888. }
  103889. if (this._emitterNode) {
  103890. result.emitter = this._emitterCreationOptions;
  103891. }
  103892. return result;
  103893. };
  103894. /**
  103895. * Parse a new ParticleSystemSet from a serialized source
  103896. * @param data defines a JSON compatible representation of the set
  103897. * @param scene defines the hosting scene
  103898. * @param gpu defines if we want GPU particles or CPU particles
  103899. * @returns a new ParticleSystemSet
  103900. */
  103901. ParticleSystemSet.Parse = function (data, scene, gpu) {
  103902. if (gpu === void 0) { gpu = false; }
  103903. var result = new ParticleSystemSet();
  103904. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  103905. scene = scene || BABYLON.Engine.LastCreatedScene;
  103906. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  103907. var system = _a[_i];
  103908. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  103909. }
  103910. if (data.emitter) {
  103911. var options = data.emitter.options;
  103912. switch (data.emitter.kind) {
  103913. case "Sphere":
  103914. result.setEmitterAsSphere({
  103915. diameter: options.diameter,
  103916. segments: options.segments,
  103917. color: BABYLON.Color3.FromArray(options.color)
  103918. }, data.emitter.renderingGroupId, scene);
  103919. break;
  103920. }
  103921. }
  103922. return result;
  103923. };
  103924. return ParticleSystemSet;
  103925. }());
  103926. BABYLON.ParticleSystemSet = ParticleSystemSet;
  103927. })(BABYLON || (BABYLON = {}));
  103928. //# sourceMappingURL=babylon.particleSystemSet.js.map
  103929. var BABYLON;
  103930. (function (BABYLON) {
  103931. /**
  103932. * This class is made for on one-liner static method to help creating particle system set.
  103933. */
  103934. var ParticleHelper = /** @class */ (function () {
  103935. function ParticleHelper() {
  103936. }
  103937. /**
  103938. * This is the main static method (one-liner) of this helper to create different particle systems
  103939. * @param type This string represents the type to the particle system to create
  103940. * @param scene The scene where the particle system should live
  103941. * @param gpu If the system will use gpu
  103942. * @returns the ParticleSystemSet created
  103943. */
  103944. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  103945. if (gpu === void 0) { gpu = false; }
  103946. if (!scene) {
  103947. scene = BABYLON.Engine.LastCreatedScene;
  103948. ;
  103949. }
  103950. var token = {};
  103951. scene._addPendingData(token);
  103952. return new Promise(function (resolve, reject) {
  103953. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  103954. scene._removePendingData(token);
  103955. return reject("Particle system with GPU is not supported.");
  103956. }
  103957. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  103958. scene._removePendingData(token);
  103959. var newData = JSON.parse(data.toString());
  103960. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  103961. }, undefined, undefined, undefined, function (req, exception) {
  103962. scene._removePendingData(token);
  103963. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  103964. });
  103965. });
  103966. };
  103967. /**
  103968. * Static function used to export a particle system to a ParticleSystemSet variable.
  103969. * Please note that the emitter shape is not exported
  103970. * @param system defines the particle systems to export
  103971. */
  103972. ParticleHelper.ExportSet = function (systems) {
  103973. var set = new BABYLON.ParticleSystemSet();
  103974. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  103975. var system = systems_1[_i];
  103976. set.systems.push(system);
  103977. }
  103978. return set;
  103979. };
  103980. /**
  103981. * Gets or sets base Assets URL
  103982. */
  103983. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  103984. return ParticleHelper;
  103985. }());
  103986. BABYLON.ParticleHelper = ParticleHelper;
  103987. })(BABYLON || (BABYLON = {}));
  103988. //# sourceMappingURL=babylon.particleHelper.js.map
  103989. var BABYLON;
  103990. (function (BABYLON) {
  103991. /**
  103992. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  103993. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  103994. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  103995. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103996. */
  103997. var VideoDome = /** @class */ (function (_super) {
  103998. __extends(VideoDome, _super);
  103999. /**
  104000. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  104001. * @param name Element's name, child elements will append suffixes for their own names.
  104002. * @param urlsOrVideo defines the url(s) or the video element to use
  104003. * @param options An object containing optional or exposed sub element properties
  104004. */
  104005. function VideoDome(name, urlsOrVideo, options, scene) {
  104006. var _this = _super.call(this, name, scene) || this;
  104007. _this._useDirectMapping = false;
  104008. // set defaults and manage values
  104009. name = name || "videoDome";
  104010. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104011. options.clickToPlay = Boolean(options.clickToPlay);
  104012. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  104013. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  104014. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104015. if (options.useDirectMapping === undefined) {
  104016. _this._useDirectMapping = true;
  104017. }
  104018. else {
  104019. _this._useDirectMapping = options.useDirectMapping;
  104020. }
  104021. _this._setReady(false);
  104022. // create
  104023. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  104024. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104025. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  104026. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104027. texture.onLoadObservable.addOnce(function () {
  104028. _this._setReady(true);
  104029. });
  104030. // configure material
  104031. material.useEquirectangularFOV = true;
  104032. material.fovMultiplier = 1.0;
  104033. material.opacityFresnel = false;
  104034. if (_this._useDirectMapping) {
  104035. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104036. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104037. material.diffuseTexture = texture;
  104038. }
  104039. else {
  104040. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104041. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104042. material.reflectionTexture = texture;
  104043. }
  104044. // configure mesh
  104045. _this._mesh.material = material;
  104046. _this._mesh.parent = _this;
  104047. // optional configuration
  104048. if (options.clickToPlay) {
  104049. scene.onPointerUp = function () {
  104050. _this._videoTexture.video.play();
  104051. };
  104052. }
  104053. return _this;
  104054. }
  104055. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  104056. /**
  104057. * Gets the video texture being displayed on the sphere
  104058. */
  104059. get: function () {
  104060. return this._videoTexture;
  104061. },
  104062. enumerable: true,
  104063. configurable: true
  104064. });
  104065. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  104066. /**
  104067. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104068. * Also see the options.resolution property.
  104069. */
  104070. get: function () {
  104071. return this._material.fovMultiplier;
  104072. },
  104073. set: function (value) {
  104074. this._material.fovMultiplier = value;
  104075. },
  104076. enumerable: true,
  104077. configurable: true
  104078. });
  104079. /**
  104080. * Releases resources associated with this node.
  104081. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104082. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104083. */
  104084. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104085. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104086. this._videoTexture.dispose();
  104087. this._mesh.dispose();
  104088. this._material.dispose();
  104089. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104090. };
  104091. return VideoDome;
  104092. }(BABYLON.Node));
  104093. BABYLON.VideoDome = VideoDome;
  104094. })(BABYLON || (BABYLON = {}));
  104095. //# sourceMappingURL=babylon.videoDome.js.map
  104096. var BABYLON;
  104097. (function (BABYLON) {
  104098. /**
  104099. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  104100. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  104101. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  104102. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104103. */
  104104. var PhotoDome = /** @class */ (function (_super) {
  104105. __extends(PhotoDome, _super);
  104106. /**
  104107. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  104108. * @param name Element's name, child elements will append suffixes for their own names.
  104109. * @param urlsOfPhoto define the url of the photo to display
  104110. * @param options An object containing optional or exposed sub element properties
  104111. */
  104112. function PhotoDome(name, urlOfPhoto, options, scene) {
  104113. var _this = _super.call(this, name, scene) || this;
  104114. _this._useDirectMapping = false;
  104115. // set defaults and manage values
  104116. name = name || "photoDome";
  104117. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104118. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104119. if (options.useDirectMapping === undefined) {
  104120. _this._useDirectMapping = true;
  104121. }
  104122. else {
  104123. _this._useDirectMapping = options.useDirectMapping;
  104124. }
  104125. _this._setReady(false);
  104126. // create
  104127. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104128. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104129. // configure material
  104130. material.opacityFresnel = false;
  104131. material.useEquirectangularFOV = true;
  104132. material.fovMultiplier = 1.0;
  104133. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  104134. _this.photoTexture.onLoadObservable.addOnce(function () {
  104135. _this._setReady(true);
  104136. });
  104137. // configure mesh
  104138. _this._mesh.material = material;
  104139. _this._mesh.parent = _this;
  104140. return _this;
  104141. }
  104142. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  104143. /**
  104144. * Gets or sets the texture being displayed on the sphere
  104145. */
  104146. get: function () {
  104147. return this._photoTexture;
  104148. },
  104149. set: function (value) {
  104150. if (this._photoTexture === value) {
  104151. return;
  104152. }
  104153. this._photoTexture = value;
  104154. if (this._useDirectMapping) {
  104155. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104156. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104157. this._material.diffuseTexture = this._photoTexture;
  104158. }
  104159. else {
  104160. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104161. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104162. this._material.reflectionTexture = this._photoTexture;
  104163. }
  104164. },
  104165. enumerable: true,
  104166. configurable: true
  104167. });
  104168. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  104169. /**
  104170. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104171. * Also see the options.resolution property.
  104172. */
  104173. get: function () {
  104174. return this._material.fovMultiplier;
  104175. },
  104176. set: function (value) {
  104177. this._material.fovMultiplier = value;
  104178. },
  104179. enumerable: true,
  104180. configurable: true
  104181. });
  104182. /**
  104183. * Releases resources associated with this node.
  104184. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104185. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104186. */
  104187. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104188. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104189. this._photoTexture.dispose();
  104190. this._mesh.dispose();
  104191. this._material.dispose();
  104192. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104193. };
  104194. return PhotoDome;
  104195. }(BABYLON.Node));
  104196. BABYLON.PhotoDome = PhotoDome;
  104197. })(BABYLON || (BABYLON = {}));
  104198. //# sourceMappingURL=babylon.photoDome.js.map
  104199. var BABYLON;
  104200. (function (BABYLON) {
  104201. BABYLON.Engine.prototype.createQuery = function () {
  104202. return this._gl.createQuery();
  104203. };
  104204. BABYLON.Engine.prototype.deleteQuery = function (query) {
  104205. this._gl.deleteQuery(query);
  104206. return this;
  104207. };
  104208. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  104209. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  104210. };
  104211. BABYLON.Engine.prototype.getQueryResult = function (query) {
  104212. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  104213. };
  104214. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  104215. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104216. this._gl.beginQuery(glAlgorithm, query);
  104217. return this;
  104218. };
  104219. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  104220. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104221. this._gl.endQuery(glAlgorithm);
  104222. return this;
  104223. };
  104224. BABYLON.Engine.prototype._createTimeQuery = function () {
  104225. var timerQuery = this.getCaps().timerQuery;
  104226. if (timerQuery.createQueryEXT) {
  104227. return timerQuery.createQueryEXT();
  104228. }
  104229. return this.createQuery();
  104230. };
  104231. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  104232. var timerQuery = this.getCaps().timerQuery;
  104233. if (timerQuery.deleteQueryEXT) {
  104234. timerQuery.deleteQueryEXT(query);
  104235. return;
  104236. }
  104237. this.deleteQuery(query);
  104238. };
  104239. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  104240. var timerQuery = this.getCaps().timerQuery;
  104241. if (timerQuery.getQueryObjectEXT) {
  104242. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  104243. }
  104244. return this.getQueryResult(query);
  104245. };
  104246. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  104247. var timerQuery = this.getCaps().timerQuery;
  104248. if (timerQuery.getQueryObjectEXT) {
  104249. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  104250. }
  104251. return this.isQueryResultAvailable(query);
  104252. };
  104253. BABYLON.Engine.prototype.startTimeQuery = function () {
  104254. var caps = this.getCaps();
  104255. var timerQuery = caps.timerQuery;
  104256. if (!timerQuery) {
  104257. return null;
  104258. }
  104259. var token = new BABYLON._TimeToken();
  104260. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104261. if (caps.canUseTimestampForTimerQuery) {
  104262. token._startTimeQuery = this._createTimeQuery();
  104263. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  104264. }
  104265. else {
  104266. if (this._currentNonTimestampToken) {
  104267. return this._currentNonTimestampToken;
  104268. }
  104269. token._timeElapsedQuery = this._createTimeQuery();
  104270. if (timerQuery.beginQueryEXT) {
  104271. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104272. }
  104273. else {
  104274. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104275. }
  104276. this._currentNonTimestampToken = token;
  104277. }
  104278. return token;
  104279. };
  104280. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  104281. var caps = this.getCaps();
  104282. var timerQuery = caps.timerQuery;
  104283. if (!timerQuery || !token) {
  104284. return -1;
  104285. }
  104286. if (caps.canUseTimestampForTimerQuery) {
  104287. if (!token._startTimeQuery) {
  104288. return -1;
  104289. }
  104290. if (!token._endTimeQuery) {
  104291. token._endTimeQuery = this._createTimeQuery();
  104292. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  104293. }
  104294. }
  104295. else if (!token._timeElapsedQueryEnded) {
  104296. if (!token._timeElapsedQuery) {
  104297. return -1;
  104298. }
  104299. if (timerQuery.endQueryEXT) {
  104300. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  104301. }
  104302. else {
  104303. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  104304. }
  104305. token._timeElapsedQueryEnded = true;
  104306. }
  104307. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104308. var available = false;
  104309. if (token._endTimeQuery) {
  104310. available = this._getTimeQueryAvailability(token._endTimeQuery);
  104311. }
  104312. else if (token._timeElapsedQuery) {
  104313. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  104314. }
  104315. if (available && !disjoint) {
  104316. var result = 0;
  104317. if (caps.canUseTimestampForTimerQuery) {
  104318. if (!token._startTimeQuery || !token._endTimeQuery) {
  104319. return -1;
  104320. }
  104321. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  104322. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  104323. result = timeEnd - timeStart;
  104324. this._deleteTimeQuery(token._startTimeQuery);
  104325. this._deleteTimeQuery(token._endTimeQuery);
  104326. token._startTimeQuery = null;
  104327. token._endTimeQuery = null;
  104328. }
  104329. else {
  104330. if (!token._timeElapsedQuery) {
  104331. return -1;
  104332. }
  104333. result = this._getTimeQueryResult(token._timeElapsedQuery);
  104334. this._deleteTimeQuery(token._timeElapsedQuery);
  104335. token._timeElapsedQuery = null;
  104336. token._timeElapsedQueryEnded = false;
  104337. this._currentNonTimestampToken = null;
  104338. }
  104339. return result;
  104340. }
  104341. return -1;
  104342. };
  104343. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  104344. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  104345. };
  104346. // We also need to update AbstractMesh as there is a portion of the code there
  104347. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  104348. var engine = this.getEngine();
  104349. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  104350. this._isOccluded = false;
  104351. return;
  104352. }
  104353. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  104354. this._isOccluded = false;
  104355. return;
  104356. }
  104357. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  104358. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  104359. if (isOcclusionQueryAvailable) {
  104360. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  104361. this._isOcclusionQueryInProgress = false;
  104362. this._occlusionInternalRetryCounter = 0;
  104363. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  104364. }
  104365. else {
  104366. this._occlusionInternalRetryCounter++;
  104367. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  104368. this._isOcclusionQueryInProgress = false;
  104369. this._occlusionInternalRetryCounter = 0;
  104370. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  104371. // if strict continue the last state of the object.
  104372. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  104373. }
  104374. else {
  104375. return;
  104376. }
  104377. }
  104378. }
  104379. var scene = this.getScene();
  104380. if (scene.getBoundingBoxRenderer) {
  104381. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  104382. if (!this._occlusionQuery) {
  104383. this._occlusionQuery = engine.createQuery();
  104384. }
  104385. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  104386. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  104387. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  104388. this._isOcclusionQueryInProgress = true;
  104389. }
  104390. };
  104391. })(BABYLON || (BABYLON = {}));
  104392. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  104393. var BABYLON;
  104394. (function (BABYLON) {
  104395. /**
  104396. * Class used to generate noise procedural textures
  104397. */
  104398. var NoiseProceduralTexture = /** @class */ (function (_super) {
  104399. __extends(NoiseProceduralTexture, _super);
  104400. /**
  104401. * Creates a new NoiseProceduralTexture
  104402. * @param name defines the name fo the texture
  104403. * @param size defines the size of the texture (default is 256)
  104404. * @param scene defines the hosting scene
  104405. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  104406. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  104407. */
  104408. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  104409. if (size === void 0) { size = 256; }
  104410. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  104411. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  104412. _this._time = 0;
  104413. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  104414. _this.brightness = 0.2;
  104415. /** Defines the number of octaves to process */
  104416. _this.octaves = 3;
  104417. /** Defines the level of persistence (0.8 by default) */
  104418. _this.persistence = 0.8;
  104419. /** Gets or sets animation speed factor (default is 1) */
  104420. _this.animationSpeedFactor = 1;
  104421. _this._updateShaderUniforms();
  104422. return _this;
  104423. }
  104424. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  104425. var scene = this.getScene();
  104426. if (!scene) {
  104427. return;
  104428. }
  104429. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  104430. this.setFloat("brightness", this.brightness);
  104431. this.setInt("octaves", this.octaves);
  104432. this.setFloat("persistence", this.persistence);
  104433. this.setFloat("timeScale", this._time);
  104434. };
  104435. /** Generate the current state of the procedural texture */
  104436. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  104437. this._updateShaderUniforms();
  104438. _super.prototype.render.call(this, useCameraPostProcess);
  104439. };
  104440. /**
  104441. * Serializes this noise procedural texture
  104442. * @returns a serialized noise procedural texture object
  104443. */
  104444. NoiseProceduralTexture.prototype.serialize = function () {
  104445. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  104446. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  104447. return serializationObject;
  104448. };
  104449. /**
  104450. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  104451. * @param parsedTexture defines parsed texture data
  104452. * @param scene defines the current scene
  104453. * @param rootUrl defines the root URL containing noise procedural texture information
  104454. * @returns a parsed NoiseProceduralTexture
  104455. */
  104456. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  104457. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  104458. return texture;
  104459. };
  104460. return NoiseProceduralTexture;
  104461. }(BABYLON.ProceduralTexture));
  104462. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  104463. })(BABYLON || (BABYLON = {}));
  104464. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  104465. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(outPosition.y,outPosition.z)).r;\nfloat fetchedG=texture(noiseSampler,vec2(outPosition.x+0.33,outPosition.z+0.33)).r;\nfloat fetchedB=texture(noiseSampler,vec2(outPosition.z-0.33,outPosition.y-0.33)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform int octaves;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<octaves; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  104466. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};